如何使用codefirst方法创建表

时间:2017-01-09 08:17:51

标签: c# entity-framework ef-code-first

我正在使用Code First方法在C#中创建登录页面,在此我尝试执行代码时遇到了很多错误。我是一个更新鲜,更新的人。

请您查看我的代码并帮助我在这方面错过了什么?

规则不会创建并获取多个错误。你的帮助可以帮助我理解这里出了什么问题。

我的班级" Class1.cs"

public class Login
    {
        [Required]
        public string username { get; set; }
       [Required]
        public string password{ get; set; }

    }
}
public class LoginContext : DbContext
{
    public LoginContext() : base("LoginDBConnectionString")
    {

        Database.SetInitializer<LoginContext>(new DropCreateDatabaseIfModelChanges<LoginContext>());
    }


    public DbSet<username> username { get; set; }
    public DbSet<password> password { get; set; }

}

Context.cs

using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data.Entity;
using Jquery1.Models;

namespace Jquery1.Models
{
    public class Logincontext: DbContext
    {
        public Logincontext () : base ("LoginDBConnectionString")
        {

        }

        public DbSet<Login> Logins{ get; set; }

    }
  }

class program
{
    static void Main(string[] args)
    {

        using (var ctx = new Logincontext())
        {
            ctx.Database.Create();
        }`enter code here`
    }
}

2 个答案:

答案 0 :(得分:1)

嗨,请允许我使用fluent api向我解释一下,请稍等一下,

首先创建DbContext

public class MyDbContext : DbContext
{
    public MyDbContext()
        : base("name=MyConnection")
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, YourApplication.Migrations.Configuration>("MyConnection")); 
    }
    public DbSet<Users> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //here you can MAP Your Models/Entities, but i am going to show you something more interesting. so keep up. 
        modelBuilder.Configurations.Add(new UsersMap());
    }
}

在您的应用根目录中创建一个迁移文件夹并在那里进行Configuration课程(为什么?!这样每次进行更改时,EF都会为您更新表格):

internal sealed class Configuration : DbMigrationsConfiguration<YourApplication.Infrastructure.Data.MyDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        //this feature on true can result in unwanted/unexpected dataloss
        AutomaticMigrationDataLossAllowed = true;
        ContextKey = "YourApplication.Infrastructure.Data.MyDbContext";
    }

    protected override void Seed(YourApplication.Infrastructure.Data.MyDbContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

现在继续并创建您的POCO课程。我试着写我的代码非常干净。这就是为什么当我在下面制作一个Model时,我为每个EntityBase创建一个Id

public class EntityBase
{
    public int Id { get; set; }
}

并将其实施到我的Model

public class User: EntityBase
{
    public string Example1{ get; set; }
    public string Example2{ get; set; }
    public string Example3{ get; set; }
}

对于映射我创建另一个类,如下所示,并使用Fluent Api

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        //declaring the table name
        ToTable("TblUser");
        //declaring primary key of the table
        HasKey(x => x.Id);
        //declaring a property from poco class is required
        Property(x => x.Example1)
            .IsRequired();
        //etc

    }
}

请注意,如果您使用的是流畅的api,则不应使用数据注释。快乐的编码。

答案 1 :(得分:0)

实体框架工作使用标准或其他的概念。如果你想要你的物品相当标准,你就不要必须提供大量信息。如果您希望表格具有不同的名称,或者您的列与标准不同,则您必须使用属性(您使用的方法)或流畅的API提供额外信息。

应该成为表的每个类都应该有一个主键。默认设置是为您的类提供属性ID,或者为属性提供类的名称,后跟Id:

public class Login
{
    public int Id {get; set;}
    public string UserName {get; set;}
    public string Password {get; set;}
}
public class MyDbContext : DbContext
{
    public DbSet<Login> Logins {get; set;}
}

这应该足以为您提供一个默认名称的表格,该名称是您的班级名称登录的复数。表中的每条记录都有三列:

  • Id:主键
  • UserName:一个字符串,在本例中可以为null
  • PassWord:一个可能为null的字符串。

您的Requires属性将确保您的UserName和Property不为null,但是他们不会阻止它们为空。我不确定这对你来说还不够。

您可以自由使用LoginId作为外键,而不是ID:

public int LoginId {get; set;}

您将看到使用的两种方法。两者都有其优点。使用Id会立即显示哪个属性是主键。 LoginId也可以用作外键。单独使用LoginId这个名称不足以查看它是主键还是外键。

对于项目为单数形式的项目集合,默认值通常为复数。在这里,您将看到Login as class,并将Logins视为此类的一组对象。

帮助我使用Entity Framework进行了大量工作的文章是this entity framework tutorial

本教程将告诉您如何使用默认值,如何使用外键创建一对多关系,多对多,各种继承策略以及如果您对默认模型不满意该怎么办。