Entity Framework 4.1 Code First: Many to many with ICollection on only one entity
Given these classes, using EF 4.1 Code First, this will (by convention) leave to a many-to-many relation between Page and Tag:
public interface ITaggable
{
ICollection<Tag> { get; set; }
}
public class Page : ITaggable
{
public virtual ICollection<Tag> { get; set; }
}
public class Tag
{
public virtual ICollection<Page> { get; set; }
}
Since I have a bunch of other classes, that implement the ITaggable
I'd have to add all these collections to Tag
:
public class Tag
{
public virtual ICollection<Pa开发者_如何学运维ge> { get; set; }
public virtual ICollection<Post> { get; set; }
public virtual ICollection<Event> { get; set; }
...
}
If I leave out these properties on Tag
EF generates a 1-to-many relation. Is there a way to leave out the ICollection<T>
on Tag
and get a many-to-many relation anyway?
(Remark: ICollection<ITaggable>
on Tag
doesn't work.)
You have to use fluent mapping:
public interface ITaggable
{
ICollection<Tag> { get; set; }
}
public class Page : ITaggable
{
...
public virtual ICollection<Tag> Tags { get; set; }
}
public class Tag
{
...
}
public class Context : DbContext
{
public DbSet<Tag> Tags { get; set; }
public DbSet<Page> Pages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Page>()
.HasMany(p => p.Tags)
.WithMany();
}
}
精彩评论