c# - EntityFramework : 1:0. .1 关系反序列化为集合

标签 c# mysql entity-framework foreign-keys

我对 entityframewrok 有疑问,它将两个表之间的 1:0..1 关系序列化为一个集合。

我的数据库中有 2 个表:

CREATE TABLE `revisiones` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  ---Irrelevant columns here---
  PRIMARY KEY (`Id`),
  ---Irrelevant constraint and foreign keys here---
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `ficha_deposito` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `IdRevision` int(11) NOT NULL,
  ---Irrelevant Columns Here---
  PRIMARY KEY (`Id`),
  UNIQUE KEY `IdRevision_UNIQUE` (`IdRevision`),
  CONSTRAINT `fk_ficdep_rev` FOREIGN KEY (`IdRevision`) REFERENCES `revisiones` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ---Irrelevant constraints here---
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

如您所见,由于独特的限制,修订可能与 none 或 1 ficha_deposito 相关。

但是在 edmx 文件中,关系被序列化为一个集合:

enter image description here

如果我尝试手动更改它(我宁愿不这样做,因为如果我必须重新生成模型,我将不得不再次手动设置该值),然后我得到一个异常:

Running transformation: Multiplicity is not valid in Role 'ficha_deposito' in relationship 'fk_ficdep_rev'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be *.

为什么我不能改变关系的多重性? revision.ficha_deposito 应该是 null 或一个简单的对象。

最佳答案

这是 EF6 限制。 EF 通过所谓的 Shared Primary Key Associations 自然地支持 一对一 关系,其中依赖实体中没有单独的FK,但PK也用作主表的FK。

当依赖实体使用单独的 FK 字段时,即使它有唯一约束支持,从 EF 的角度来看它仍然是 一对多 关系。我无法比 One-to-One Foreign Key Associations 更好地解释它了。 :

As you may have noticed, both associations in the fluent API code has been configured as a many-to-one — not one-to-one, as you might have expected. The reason is simple: Code First (and EF in general) does not natively support one-to-one foreign key associations. In fact, EF does not support any association scenario that involves unique constraints at all.

然后

The second limitation that this lack of support impose to us is more important: one to one foreign key associations cannot be bidirectional (e.g. we cannot define a property for the User on the Address class).

好消息是此类支持已添加到 EF Core,因此当它可用时(v1.1 或更高版本),您将能够建立此类关系。在那之前,您应该接受一对多

关于c# - EntityFramework : 1:0. .1 关系反序列化为集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39101297/

相关文章:

c# - 计算盒子上的力

c# - 为什么在 WCF 应用程序的 Web.config 文件中添加 httpRuntime targetFramework 可以解决与 TLS 相关的连接问题?

Mysql - 连接同一张表的数据

c# - 代码优先更改桥实体表的名称

c# - 如何从多用户编辑中锁定 asp.net 页面?

c# - 如何从 Azure 数据工厂在 Databricks 上运行 .Net spark 作业?

用于处理表名中不区分大小写的 PHP MYSQL 配置

mysql - 我可以在mysql中添加时间和日期吗?

c# - 如何将这 2 种方法重构为 1 种方法?

LINQ:在 LINQ let 中使用三元 ( ?: ) 是不够的,需要 "IF"但似乎无法让它工作