【问题标题】:Entity Framework POCO Relationships实体框架 POCO 关系
【发布时间】:2012-07-19 15:13:08
【问题描述】:

我正在尝试实现实体框架的代码优先方法。我有四个实体UserInfoClientAdminAccount。我想要这样的关系:

  • 每个Client 都有一个UserInfo
  • 每个Admin 都有一个`UserInfo
  • 每个Account 都与一个用户(UserInfo) 链接

假设这些东西,我编写了 POCO 模型。对于我想要的关系,是否正确?我错过了什么吗?

public class UserInfo
    {
        public int UserInfoID { get; set; }
        public Name Name { get; set; }
        public Address Address { get; set; }
        public Contact Contact { get; set; }
    }

public class Admin
    {
        public int AdminID { get; set; }
        public int UserInfoID { get; set; }
        [ForeignKey("UserInfoID")]
        public virtual UserInfo UserInfo { get; set; }
    }

public class Client
    {
        public int ClientID { get; set; }
        public CompanyDetails CompanyDetails { get; set; }
        public int UserInfoID { get; set; }
        [ForeignKey("UserInfoID")]
        public virtual UserInfo UserInfo { get; set; }
    }

 public class Account
    {
        public int AccountID { get; set; }
        [Required, Column("Balance"), Display(Name = "Account Balance")]
        public double Balance { get; set; }
        public int UserInfoID { get; set; }
        [ForeignKey("UserInfoID")]
        public virtual UserInfo UserInfo { get; set; }
    }

【问题讨论】:

  • 你为什么不试试看?
  • 我做到了。我想确保我朝着正确的方向前进。

标签: asp.net-mvc-3 entity-framework ef-code-first poco code-first


【解决方案1】:

根据您的要求,您所拥有的似乎是正确的,但是在使用 Code First 配置您的实体时,我个人更喜欢实体框架模型构建器。

使用模型构建器意味着您的 POCO 实体没有任何属性,这反过来意味着您不需要 EF 引用来使用实体。

在这里查看我的文章,了解有关如何使用模型构建器的更多信息:http://blog.staticvoid.co.nz/2012/07/entity-framework-navigation-property.html

【讨论】:

  • 谢谢 :) 真的很想听到任何建议以使其更容易
  • 您可以使用模型构建器添加主键和外键实现以及导航属性。无论如何,对于像我这样的初学者来说,您的帖子非常清晰易读:)
  • 是的,我在写的时候想过,我可能会添加它,因为它有点重要
猜你喜欢
  • 1970-01-01
  • 2011-08-21
  • 2011-04-06
  • 2012-03-08
  • 1970-01-01
  • 2012-03-22
  • 1970-01-01
  • 2011-03-04
  • 2016-03-17
相关资源
最近更新 更多