【问题标题】:How to create tables in codefirst approach如何在代码优先的方法中创建表
【发布时间】:2017-01-09 08:17:50
【问题描述】:

我正在使用 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`
    }
}

【问题讨论】:

  • 您将不得不提供更多信息。你的代码在哪里?什么错误?它们被扔到哪里去了?
  • @David Thnx,附上我的代码
  • 提供您在这里遇到的错误,否则人们将很难帮助您,为什么两个示例中的 LoginContext 不同?用户名和密码类在哪里? DbSet 代表数据库中的一个表,我认为您将它们与列混淆了

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


【解决方案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 时,我为每个Id 创建一个EntityBase

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

    }
}

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

【讨论】:

  • 另外,不要忘记在生产环境中禁用自动迁移。您当前的配置可能会导致不需要/意​​外的数据丢失。
【解决方案2】:

实体框架使用标准或其他概念。如果您希望您的物品相当标准,您不必提供很多信息。如果您希望您的表具有不同的名称,或者您的列与标准不同,则必须使用 Attributes(您使用的方法)或 fluent 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;}
}

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

  • Id:主键
  • 用户名:一个字符串,在这种情况下可能为空
  • 密码:一个可能为空的字符串。

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

您可以免费使用 LoginId 作为外键,而不是 Id:

public int LoginId {get; set;}

您将看到两种方法都被使用。两者都有自己的优势。使用 Id 会立即向您显示哪个属性是主键。 LoginId 也可以用作外键。仅靠名称 LoginId 不足以判断是主键还是外键。

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

对我使用 Entity Framework 有很大帮助的文章是this entity framework tutorial

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多