Can I create a separate table for a single Collection property using Entity Framework code first?

I have a class Foo with an ICollection<string>. To be able to store this through Entity Framework, I have created a class Bar with an Id and Value property. Entity Framework creates a table for Bar with a foreign key column to Foo. This works well.

The problem is that I have a whole bunch of classes with such a ICollection<string>. I converted them all to ICollection<Bar>. The result however is that the Foo table now contains a foreign key column for every class that has an ICollection<Bar> (10+).

While I understand that it's necessary to do this to have those relationships work in the database, the database diagram doesn't get more intuitive this way.

I was thinking that, like in a many to many relationship, I would like to have a table in between each of those relationships. For example,

    <li>a table Foo_Bar with two columns: Foo_Id and Bar_Id for the relationship between Foo and Bar and another table Baz_Bar with Baz_Id and Bar_Id.</li> </ul>

    To achieve this, I can create a sub class of Bar (e.g. FooBar) for every relationship; change the collection to use those (e.g. ICollection<FooBar>); and let EF create the database using the table per type (e.g. by decorating FooBar with [Table("Foo_Bar")]) approach for these types. But I would like to prevent having to create all these empty classes.

    I wonder if it is possible to somehow specify this behaviour just based on the property. Something like this:

    public class Foo { [Table("Foo_Bar")] public ICollection<Bar> Bars { get; set; } }

    On a side note: If this approach is a bad idea in the first place, don't hesitate to let me know :).


    to summarize comments:

    what you want (i.e.: 5 tables) is a many to many relation for Entity Framework.

    By conventions you get it by setting a collection on both entities

    Foo { ICollection<Bar> Bars } Foo { ICollection<Foo> Foos }

    if you don't want the reverse collections (Foos) then you have to setup the relation by the fluent API.

    modelBuilder.Entity<Foo>.HasMany(x => x.Bars).WithMany()

    AFAIK there is no annotation allowing to reach this last result by using the Annotations.

    You then have to handle by hand the unicity of Foo for a Bar. A solution may be a unique constraint on the Bar Key of the join table created by EF.

    人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:Can I create a separate table for a single Collection property using Entity Framework code first?