How to create tables with EntityFrameworks and that are added to the model by code? [closed]

-1

I am developing a Human Resources System, where I have used EntityFrameworks, get to the part that I need to create Tables through the application and be able to use them later. Can You Create Tabas Dynamically with EF? What would be the Code?

    
asked by byok22 22.12.2017 в 20:17
source

1 answer

1
  • Create a new project of any kind, if it is a web application use the templates of Web API and MVC if you want to work with REST , if you only want to make a website with a Bootstrap template, select only MVC
  • You create a model with the class to which you want to create the table, you declare its properties

For example


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace TutorialEntityFramework.Models
{
    public class BlogPost
    {
        public int Id { get; set; }
        [Required]
        [StringLength(200)]
        public string Titulo { get; set; }
        [Required]
        public string Contenido { get; set; }
        [StringLength(100)]
        public string Autor { get; set; }
        public DateTime Publicacion { get; set; }
    }
}
  • Create your class that you will inherit from DbContext

Example


using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace TutorialEntityFramework.Models
{
    public class BlogContext: DbContext
    {
        public BlogContext()
            : base("DefaultConnection")
        {

        }
        public DbSet BlogPosts { get; set; }

    }
}
  • Open Nuget Package Manager and execute the command enable-migrations
  • In the created migrations folder, open the file configuration.cs
  • Add line '' and save
  • Go back to the Nuget Package Manager and execute the update-database command
  • You already have your database created, now, you can use it

PS: You're supposed to have your connectionString set in your web.config before doing all that

Example


<connectionStrings>
    <add name="DefaultConnection" connectionString="data source=TU_SERVIDOR;initial catalog=NOMBRE_DE_BD;integrated security=false;persist security info=True;User ID=TU_NOMBRE_DE_USUARIO;Password=TU_CLAVE_DE_BD" providerName="System.Data.SqlClient"/>
  </connectionStrings>
    
answered by 22.12.2017 в 20:32