【问题标题】:How to properly setup model, POCO class?如何正确设置模型、POCO 类?
【发布时间】:2013-04-13 19:56:53
【问题描述】:

我对如何正确设置我的模型有点困惑。下面你会看到我的 POCO,我想知道如何自动增加 ID,以及是否有必要设置数据注释 [Key]。是否有某种命名约定可以使 EF 识别 ID/主键,还是我必须使用 [Key] 数据注释?

还有必要在子实体中设置[Key]数据注解吗?

    public class User
{
    [Key]
    public int UserId { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public DateTime Reg { get; set; }
    public virtual ICollection<Stats> Stats { get; set; } 
}

public class Stats
{
    [Key]
    public int StatId { get; set; }
    public string Age { get; set; }
    public string Height { get; set; }
    public string Weight { get; set; }
    public bool Sex { get; set; }
}

public class BodylogContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Stats> Stats { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<BodylogContext>(null);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

【问题讨论】:

    标签: c# asp.net-mvc entity-framework data-annotations poco


    【解决方案1】:

    您应该查看 Entity Framework Code First 教程以获取更多详细信息。

    具体来说,就您而言,还有一些基本规则(免责声明:)我并不想涵盖所有内容只是一些基本规则......

    • 您可以删除[Key] -
      如果您使用&lt;Entity&gt;Id - 或仅使用Id,则默认情况下将其制成PK。
      'FK-s' 和相关的 navigation properties 也是如此(除了 &lt;Property&gt;Id 也按约定映射),
      它不区分大小写。

    • Identity 默认情况下 - 对于有意义的 pk 类型 - int、long... - 不适用于字符串,

    • 如果你有 more than one pk - 那么你需要用 Key 来“装饰”它 - 或者在流利的配置中,

    等等……

    注意:您可以在 Fluent 配置中调整和删除 conventions
    同样从 EF6,您将能够为您的代码定义一个新的。

    我的建议:开启Migrations 并查找迁移 脚本代码(.cs 文件)生成的文件。它总是有清晰的 什么是键、索引等的描述。了解如何使用的最佳方式 实际创建了 Db。

    【讨论】:

    • 谢谢你,我发现这真的很有帮助,感谢你的回答。
    【解决方案2】:

    我也刚开始使用 MVC,我发现 this 教程回答了您提出的大部分问题。

    默认情况下,实体框架将名为 ID 或 classnameID 的属性解释为主键。因此,在您的 User 类中,您不需要 UserId 属性上的 [Key] 属性。在您的 Stats 类中,该属性与该类的名称不匹配(您已将名称复数),因此您需要该属性。

    http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      相关资源
      最近更新 更多