实体框架多对多不节省

本文关键字:节省 实体 框架 | 更新日期: 2023-09-27 18:11:17

我有一个简单的多对多。产品类别。每个都有另一个的虚拟列表。我创建了一个像这样的产品:

product = new Product()
{
    AccountId = this.AccountId,
    Name = this.ProductName,
    Price = this.ProductPrice,
    Slug = this.ProductSlug,
    Sku = this.ProductSku,
    Favorite = true,
    Categories = new List<Category>()
                {
                    category 
                }
};
product.Id = productManager.Save(product);

然后,当我去保存它时,它不会保存多对多。我在谷歌上搜索并尝试了这段代码的许多不同变体,但仍然一无所获:

public new String Save(Product data)
{
    try
    {
        var entity = GetById(data.Id);
        if (entity == null)
        {
            this.Context.Set<Product>().Add(data);
        }
        else
        {
            this.Context.Entry(entity).CurrentValues.SetValues(data);
        }
        data.Id = this.Context.SaveChanges();
        var product = Context.Products
            .Include("Categories")
            .FirstOrDefault(t => t.Id == data.Id);
        /**
            * Categories
            */
        var categories = this.Context.Categories
            .Where(t => t.AccountId == data.AccountId);
        var productCategories = new List<Category>();
        if (data.SelectedCategoryIds != null && data.SelectedCategoryIds.Any())
        {
            productCategories.AddRange(categories
                .Where(category => data.SelectedCategoryIds.Contains(category.Id)));
        }
        product.Categories.Clear();
        product.Categories.AddRange(productCategories);
        this.Context.SaveChanges();
        return data.Id;
    }
    catch (Exception ex)
    {
        Log.Error(ex);
        return null;
    }
}

我在这里错过了什么?为什么它不能保存我的多对多类别?

实体框架多对多不节省

从技术上讲,这不是一个答案,但对于注释来说太长了,需要说出来。看起来你在尝试抽象一些实体框架的东西,但这是绝对错误的方式。例如,在我的一个项目中,我有一个服务,它将实体框架从我的应用程序的其余部分抽象出来,下面是其中的一些相关代码来演示它们的区别:

public virtual void Update<TEntity>(TEntity entity)
    where TEntity : class
{
    context.Set<TEntity>().Attach(entity);
    context.Entry(entity).State = EntityState.Modified;
}
public virtual void Save()
{
    try
    {
        context.SaveChanges();
    }
    catch (DbEntityValidationException ex)
    {
        var errorMessages = ex.EntityValidationErrors
            .SelectMany(x => x.ValidationErrors)
            .Select(x => x.ErrorMessage);
        var fullErrorMessage = string.Join("; ", errorMessages);
        var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
        throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
    }
}

那么,在我的应用程序中,这就是所发生的一切:

var entity = new Something { ... };
service.Update<Something>(entity);
service.Save();
所以,上面的代码中有很多内容,所以让我后退一分钟。首先,我的服务利用泛型方法,因此我可以处理任何实体,而不必编写新的方法或服务类。<TEntity>的东西是什么使它工作,并不是严格要求。同样,当我稍后做Update<Something>时,我使用这个泛型方法,因此指定我正在使用的类,在本例中是Something。您唯一需要注意的部分是我的Update<>方法的这两行,我将对其进行修改以适应您的情况:
context.Set<Product>().Attach(product);
context.Entry(product).State = EntityState.Modified;
然后,保存更改(从我的Save方法)所必需的唯一其他事情:
context.SaveChanges();

就是这样。如果这段代码不足以更新你的实体,那么坦白地说,你做错了,你需要展开你的代码,找出那是什么。