EF代码优先:一对一的单向关系 [英] EF Code First: One-to-One One-way Relationship

查看:231
本文介绍了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代码优先:一对一的单向关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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