开发者

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

开发者 https://www.devze.com 2023-03-19 20:47 出处:网络
In Linq to SQL I could specify a relationship that didn\'t have to depen开发者_StackOverflow中文版d on the foreign keys and pks existing in the database, useful for creating composite relationships li

In Linq to SQL I could specify a relationship that didn't have to depen开发者_StackOverflow中文版d 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...


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消