无法确定关联的主要目的 [英] Unable to determine the principal end of an association

查看:76
本文介绍了无法确定关联的主要目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种关联中,我收到错误消息无法确定类型'Foo'和'Bar'之间的关联主体。必须使用fluent API或数据注释。

In this kind of association I get the error "Unable to determine the principal end of an association between the types 'Foo' and 'Bar'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations."

public class Foo
{
    public int Id { get; set; }

    public int? MainBarId { get; set; }
    public virtual Bar MainBar { get; set; }

    [InverseProperty("Foo")]
    public virtual ICollection<Bar> Bars { get; set; }
}

public class Bar
{
    public int Id { get; set; }

    public int FooId { get; set; }
    public virtual Foo Foo { get; set; }

    public int? OldFooId { get; set; }
    public virtual Foo OldFoo { get; set; }
}

此处Foo有一组Bars,并且可能有一个Main Bar( MainBar)。 Bar始终与Foo相关联,但可以引用另一个Foo(OldFoo)。

Here the Foo has a collection of Bars and could have a main Bar (MainBar). The Bar always was associated with a Foo but could have a reference to another Foo (OldFoo).


  1. 如何在EF中使用数据映射注释?

  2. 如果无法使用数据注释,如何使用流利的语言?


推荐答案

通过 [InverseProperty( Foo)] ,您告诉EF Bar.Foo Foo.Bars 是一对多关联的配对属性,所以很清楚。

By [InverseProperty("Foo")] you tell EF that Bar.Foo and Foo.Bars are paired properties in a one to many association, so that's clear.

然后在那里是 Foo.MainBar Bar.OldFoo 。 EF不知道它们之间的关系。它们可以一对一地配对,它们可以是独立的,即在另一侧具有许多多重性。因此,您必须告诉EF。

Then there are Foo.MainBar and Bar.OldFoo. EF does not know how these are related. They could be paired in a one-to-one association, they can be independent, i.e. with a "many" multiplicity on the other side. So you have to tell EF.

我假设属性是独立的,即 Bar 可以具有 OldFoo ,而不要求此 Bar Foo MainBar 同时。这样就足以为EF提供有关以下属性之一的信息:

I assume that the properties are independent, i.e. that a Bar can have an OldFoo without the requirement that this Bar is Foo's MainBar at the same time. Then it is enough to give EF information about one of the properties:

modelBuilder.Entity<Bar>().HasOptional(f => f.OldFoo).WithMany()
    .HasForeignKey(f => f.OldFooId);

modelBuilder.Entity<Foo>().HasOptional(f => f.MainBar)
    .WithRequired(b => b.OldFoo)

由于没有与这些关联的一个末端配对的逆属性,因此无法使用数据注释(没有可以用属性装饰的属性。

As there are no inverse properties paired with these "one" ends of the associations you can't do this with data annotations (there are no properties to adorn with attributes).

这篇关于无法确定关联的主要目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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