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

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

问题描述

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

We are using EF 4.1 and the fluent API to get data from a legacy database (can't modify the database). We're having a problem creating a relationship between two tables where the related columns are NOT primary and foreign keys.

使用下面的类,我们将如何配置一个报告和RunStat之间的许多关系,使Report.RunStats将返回ReportCode字段相等的所有RunStat实体。

With the classes below, how would we configure the a one to many relationship between Report and RunStat such that Report.RunStats would return all 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; }
}

基本上我想使用Fluent API来配置EF来认为报表.ReportCode是ForeignKey和RunStat.ReportCode是PrimaryKey。

Basically I want to use the Fluent API to configure EF to think that Report.ReportCode is the ForeignKey and RunStat.ReportCode is the PrimaryKey.

推荐答案

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

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.

实体框架不支持唯一键。如果您想在报告 RunStat 之间存在一对多的关系,您的从属表( RunStat )必须包含值为 Report.ReportKey 的列。没有其他方法可以自动进行,否则您必须简单地将其定义为自定义属性,并在需要时手动填充实体框架。

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天全站免登陆