【问题标题】:Relationships with EntityFramework Code First using DataAnnotations使用 DataAnnotations 与 EntityFramework Code First 的关系
【发布时间】:2011-12-22 12:42:14
【问题描述】:

我有三个表,它们之间有以下关系:

Account {
   public int Id;
}

Job {
   public int Id;
   public int AccountId;
}

Practice {
   public int Id;
   public int AccountId;
   public string Name;
}

我希望能够通过 Job 对象访问 Practice 对象,如下所示:

Job.Account.Practice.Name

数据库结构是预先存在的,因此无法更改它。我想让 EF 提供对这种关系的访问,我相信它可以。我确实通过将 ICollection 导航属性放在 Account 类的 Practice 上并使用 ForeignKey 注释 Practice 类上的 Account 导航属性来使其工作,但必须有一种方法可以在不使用集合的情况下做到这一点。

那么,问题是,我应该尝试使用哪些数据注释属性来获得所需的结果?

【问题讨论】:

    标签: entity-framework-4 data-annotations code-first


    【解决方案1】:

    说明

    您不需要 DataAnnotation 属性来执行此操作。在 Codefirst 中,您可以执行以下操作。实体框架将生成您为您描述的表。

    样本

    Account {
       public int Id;
    }
    
    Job {
       public int Id;
       public virtual Account Account;
    }
    
    Practice {
       public int Id;
       public virtual Account Account;
       public string Name;
    }
    

    如果您还想在您的工作/实践实体中添加一个 ìnt 列 (AccountId),您可以使用模型构建器执行此操作。实体框架只创建一个外键列,如您所愿。

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Job>.HasRequired(x => x.Account).WithMany().HasForeignKey(x => x.Accountid);
     //
    }
    

    更多信息

    ScottGu - Using EF “Code First” with an Existing Database

    更新

    您可以使用Entity Framework Power Tools CTP1 生成 现有数据库中的模型。

    【讨论】:

    • 感谢您的回答,但我正在使用现有数据库。当我尝试您的建议时,我收到以下信息:“无法确定类型 'Practice' 和 'Account' 之间关联的主体端。必须使用关系流式 API 或数据显式配置此关联的主体端注释。”
    • 我认为您应该使用 Entity Framework Power Tools。有一个链接,现在在我的答案中。希望这会有所帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多