使用 Entity Framework 4.1 Fluent API 在非主键字段上创建关联 [英] Create association on non-primary key fields with Entity Framework 4.1 Fluent API

查看:23
本文介绍了使用 Entity Framework 4.1 Fluent API 在非主键字段上创建关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

We are using EF 4.1 and the fluent API to get data from a legacy database (that we are not permitted to change). We are having a problem creating a relationship between two tables where the related columns are not primary and foreign keys.

With the classes below, how would we configure the one-to-many relationship between Report and RunStat such that Report.RunStats would return all of the RunStat entities where the ReportCode fields are equal?

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; }
}

Basically, I want to use the Fluent API to configure EF such that it considers Report.ReportCode to be the foreign key and RunStat.ReportCode to be the primary key.

解决方案

It is not possible. Relations in EF follows exactly same rules as in the database. It means that principal table must have unique identifier which is referenced by dependent table. In case of database the identifier can be either primary key or unique column(s) of principal table. Otherwise it is not valid relation.

Entity framework doesn't support unique keys. If you want to have one-to-many relation between Report and RunStat your dependent table (RunStat) must contains column with value of Report.ReportKey. There is no other way to make it automatic - otherwise you must simply make it custom property and fill it from entity framework manually when you need it.

这篇关于使用 Entity Framework 4.1 Fluent API 在非主键字段上创建关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆