且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

添加项目有很多一对多的关系在实体框架

更新时间:2022-12-30 19:11:55

使用相同的上下文实例为您的操作的整个加工和你的生活会更容易:

Use the same context instance for the whole processing of your operation and your life will be much easier:

using (var ctx = new MyContext())
{
    Article article = ctx.Articles.Single(a => a.Id == articleId);
    Tag tag = ctx.Tags.SingleOrDefalut(t => t.UrlSlug == tagUrl);
    if (tag == null) 
    {
       tag = new Tag() { ... }
       ctx.Tags.AddObject(tag);
    }

    article.Tags.Add(tag);
    ctx.SaveChanges();
}

如果您不希望从数据库中加载的文章(查询是多余的,如果你知道这篇文章的存在),可以使用:

If you don't want to load the article from database (that query is redundant if you know that article exists) you can use:

using (var ctx = new MyContext())
{
    Article article = new Article() { Id = articleId };
    ctx.Articles.Attach(article);

    Tag tag = ctx.Tags.SingleOrDefalut(t => t.UrlSlug == tagUrl);
    if (tag == null) 
    {
       tag = new Tag() { ... }
       ctx.Tags.AddObject(tag);
    }

    article.Tags.Add(tag);
    ctx.SaveChanges();
}