Create association on non-primary key fields with Entity Framework 4.1 Fluent API(使用 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 在非主键字段上创建关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Entity Framework 4.1 Fluent API 在非主键字段上创建关联
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01