使用Entity Framework 4.1 Fluent API在非主键字段上创建关联

GoC*_*ado 15 c# entity-framework foreign-keys primary-key entity-framework-4.1

我们使用EF 4.1和流畅的API从遗留数据库中获取数据(我们不允许更改).我们在创建两个表之间的关系时遇到问题,其中相关列不是主键和外键.

使用下面的类,我们如何配置之间的一对多关系Report,RunStat以便Report.RunStats返回字段相等的所有RunStat实体ReportCode

public class Report
{
    [Key]
    public int ReportKey { get; set; }
    public string Name { get; set; }
    public int ReportCode { get; set; } // Can we associate on this field?
    public virtual ICollection<RunStat> RunStats { get; set; }
}

public class RunStat
{
    [Key]
    public int RunStatKey { get; set; }
    public int ReportCode { get; set; }
    public DateTime RunDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

基本上,我想使用Fluent API配置EF,使其认为Report.ReportCode是外键并RunStat.ReportCode成为主键.

Lad*_*nka 11

这不可能.EF中的关系遵循与数据库中完全相同的规则.这意味着主表必须具有唯一标识符,该标识符由依赖表引用.在数据库的情况下,标识符可以是主表的主键或唯一列.否则它是无效的关系.

实体框架不支持唯一键.如果你想有一个之间对多的关系ReportRunStat你的依赖表(RunStat)必须包含的值列Report.ReportKey.有没有其他办法让它自动-否则,你只是必须使其自定义属性,并从实体框架手工填写它,当你需要它.

  • 投票将其添加为实体框架中的新功能http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1050579-unique-constraint-ie-candidate-key-support (2认同)