EF代码优先:一对一的单向关系

编程入门 行业动态 更新时间:2024-10-24 09:19:43
本文介绍了EF代码优先:一对一的单向关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我通常具有以下结构:

MyClass public virtual ICollection<Version> Versions { get; set; } public virtual Version CurrentVersion { get; set; }

也就是说,有一个东西列表,有些类都指向该列表,并且该列表中的一个特定项目-许多版本的当前版本,事件列表中的下一个即将发生的事件,等等。

That is, there is a list of stuff, and some class both points to that list, and one specific item in that list - either the current version of many versions, the next upcoming event in a list of events, etc.

在我的模式中,我想要最后是一个从Version指向MyClass的外键-可以正常工作。但是然后我想要一个外键,从MyClass指向代表CurrentVersion属性的Version,而没有外键指向后方-我不希望多余的存储空间或麻烦告诉Version的MyClass是CurrentVersion的版本(如果有)。换句话说,我希望第二种关系是从MyClass到Version的单向关系,即使它是一对一的。

In my schema what I'd like to end up with is a Foreign Key pointing from Version to MyClass - that much works out properly. But then I'd like a Foreign Key pointing from MyClass to Version representing the CurrentVersion property, with no Foreign Key pointing back - I don't want the extra storage or bother of telling a Version what MyClass it's the CurrentVersion for, if any. Put another way, I'd like this second relationship to be one-way from MyClass to Version, even though it's one-to-one.

EF Code First提供的功能相反,我是第一个属性上的正常一对多,从版本到MyClass的FK,但是第二个属性上是完整的一对一关系,而FK指向两个方向-因此,版本以MyClass_Id和MyClass_Id1结尾。

What EF Code First gives me instead is the normal one-to-many on the first property, with the FK from Version to MyClass, but then a full one-to-one relationship on the second property with an FK pointing in both directions - so the underlying schema for Version ends up with MyClass_Id and MyClass_Id1.

因此,有没有办法在不借助Fluent API的情况下在EF Code First中获得单向关系?看起来好像是System.ComponentModel.DataAnnotations.Schema.InverseProperty,但它似乎没有提供说不生成一个的方法。

So, is there a way to get a one-way relationship in EF Code First without resorting to the Fluent API? It looked like maybe System.ComponentModel.DataAnnotations.Schema.InverseProperty had a shot at it, but it didn't seem to offer a way to say "Don't generate one."

推荐答案

关键是在指向该属性的属性上指定InverseProperty,以便EF意识到这是多对多的,而不是一对多的。

The key is to specify the InverseProperty on the property that points back, so that EF realizes it's to the Many-to-Many, not to the One-to-One.

public class MyClass { public int Id { get; set; } public Version CurrentVersion { get; set; } public ICollection<Version> Versions { get; set; } } public class Version { public int Id { get; set; } [InverseProperty("Versions")] public Versioned Versioned { get; set; } }

更多推荐

EF代码优先:一对一的单向关系

本文发布于:2023-11-14 13:52:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587392.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   关系   EF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!