EF4.1 (code first) - How to specify a composite relationship

北战南征 提交于 2019-12-10 21:34:46

问题


In Linq to SQL I could specify a relationship that didn't have to depend on the foreign keys and pks existing in the database, useful for creating composite relationships like this:

public class Equipment_CableNormalised
{
    ...

    [Association(ThisKey = "EquipmentId,PortNumber", OtherKey = "EquipmentId,PortNumber", IsForeignKey = false)]
    public List<EquipmentPort> EquipmentPorts
    {
        get; set;
    }

}

This then generated the sql similar to " .. join EquipmentPorts EP on EP.EquipmentId = blah and EP.PortNumber = Blah".

Can I do the same sort of thing in EF4.1 (using annotations or fluent api)? I know you can specify composite keys and use the [Keys] and [ForeignKeys] attributes, but this relationship doesn't map to keys...


回答1:


How does the sample relation from your code works? I expect that EquipementId must be either PK or unique key (not supported in both L2S and EF) on one side because otherwise the relation could not exist (both one-to-one and one-to-many demands unique principal). Once it is PK on one side the port number is redundant.

Code first allows only mapping to keys. If you have existing database you can cheat it in your model and map new relations in the same way as you would map existing but you still have to follow simple rule - properties in principal are primary keys, properties in dependent entity are mapped as foreign keys.

If you want EF to generate DB for you, you will always have all relations in the database.




回答2:


Use HasKey http://www.ienablemuch.com/2011/06/mapping-class-to-database-view-with.html

Either use HasKey, put this on OnModelCreating

 modelBuilder.Entity<SalesOnEachCountry>().HasKey(x => new { x.CountryId, x.OrYear });   

Or use Key Column Order

public class SalesOnEachCountry
{        
    [Key, Column(Order=0)] public int CountryId { get; set; }
    public string CountryName { get; set; }
    [Key, Column(Order=1)] public int OrYear { get; set; }
     
    public long SalesCount { get; set; }      
    public decimal TotalSales { get; set; }
}

Regarding your question about foreign key, I haven't yet tried the pure code(OnModelCreating) approach, perhaps you can just put two ForeignKey attribute on child class itself, might need to put Column Order too.

This could be the answer composite key as foreign key

That answer confirms my hunch that you could put two ForeignKey attributes on child class itself.



来源:https://stackoverflow.com/questions/6647604/ef4-1-code-first-how-to-specify-a-composite-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!