且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架 InverseProperty 注释使用

更新时间:2023-11-22 13:59:28

首先,这看起来很奇怪:您正在创建多个映射到具有不同名称的同一个对象 q?

First, This looks strange : you are creating multiple mapping to the same object qwith different names ?

 [InverseProperty("Person")]
 public List<Hobbies> Sports {get;set;}

 [InverseProperty("Person")]
 public List<Hobbies> Art {get;set;}

 [InverseProperty("Person")]
 public List<Hobbies> Reading {get;set;}

应该是这样的:

[InverseProperty("Person")]
public virtual List<Hobbies> Hobbies {get;set;}

[NotMapped]
public List<Sport> Sports 
{
    get
    {
        return this.Hobbies.OfType<Sport>().ToList();
    }
}


[NotMapped]
public List<Art> Art 
{
    get
    {
        return this.Hobbies.OfType<Art>().ToList();
    }
}


[NotMapped]
public List<Reading> Readings 
{
    get
    {
        return this.Hobbies.OfType<Reading>().ToList();
    }
}

如果你在抽象类中设置了Person属性,那么映射必须是抽象类.

If you set the property Person in the abstract class, then the mapping must be to the abstract class.

否则,您必须在抽象类中声明 PersonId,然后使用属性 [ForeignKey("PersonId")] 在每个具体类中设置 Person 属性.但是这个解决方案很奇怪.

Otherwise, you have to declare the PersonId in the abstract class and then set the Person property in every concrete class using the attribute [ForeignKey("PersonId")]. But this solution is pretty strange.

其次,如果你想为 Person 指定 ForeignKey,你应该使用:

Secondly, if you want to specify the ForeignKey for the Person, you should use :

[ForeignKey("PersonID")]
public virtual Person Person {get;set;}

第三:你确定你不需要 M-N 关系吗?你真的希望每个人都创造新的爱好吗(你最终会有多次驾驶"(或其他)作为爱好).

Third : Are you sure you don't need M-N relation? Do you really want every people to create new Hobbies (you would finally have multiple times "Driving" (or whatever) as a hobby).