Entity framework 4 many-to-many insertion?

我的未来我决定 提交于 2019-12-02 11:02:54

I think that this is what you want.

var tag = context.Tags.FirstOrDefault(x=>x.Name == name);
if (tag == null)
    context.Tags.AddObject(tag = new Tag { Name = name });
if (!post.Tags.Contains(tag))
    post.Tags.Add(tag);

Happy New-Year coding))

Dan Atkinson

I would advise against maintaining many-to-many relationships in your database.

You should consider creating a lookup table called something like PostTag or PostTagLookup.

This would consist of two columns - PostId and TagId.

Entity framework handles lookup tables wonderfully, as mentioned by @Moyo in his answer:

Entity Framework will convert the mapping table into a collection of entities on both sides and the table itself will essentially disappear.

I can't seems to get it working without the Id for the Lookup table, this is what I've done to make it work. Might not be the best and most efficient way but it's working:

public class PostTagLookup
{
    public int Id { get; set; }
    public int PostId { get; set; }
    public int TagId { get; set; }

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