Entity Framework InverseProperty annotation usage

前端 未结 1 421
陌清茗
陌清茗 2021-01-28 15:50

if I have the following models, am I using the InverseProperty correctly?

class Person {
 public int PersonID {get;set;}

 [InverseProperty(\"Person\")]
 public          


        
相关标签:
1条回答
  • 2021-01-28 16:06

    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;}
    

    It should be something like :

    [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();
        }
    }
    

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

    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.

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

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

    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).

    0 讨论(0)
提交回复
热议问题