使用存储库模式在实体框架中添加带有相关子对象的记录

问题描述 投票:0回答:1

我在向数据库添加一个包含与现有对象的关系的实体时遇到麻烦。我搜索了很多,却找不到合适的解决方案。我将尽可能简单地描述它。

public class Store : IEntity
{
    public int StoreId { get; set; }
    public string StoreName { get; set; }

    public virtual Address Address { get; set; }

    public virtual Contractor Contractor { get; set; }
}

    public class Product : IEntity
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal Price { get; set; }
    public virtual Store Store { get; set; }
}

并且在存储库中添加这样的记录。这是通用类

        public TEntity Add(TEntity entity)
    {
        using (var context = new TContext())
        {
            var addedEntity = context.Entry(entity);
            addedEntity.State = EntityState.Added;
            context.SaveChanges();
            return entity;
        }
    }

现在当我尝试添加新记录时

var store = storeManager.GetBy(x => x.StoreId == 1);

var product = new Product() { ProductName = "Bananas", Store = store }; 

productManager.Add(product);

productManager.GetAll().ForEach(x => Console.WriteLine(x.ProductName + " " + x.Store.StoreId));

商店关系被添加为新商店,并且它具有新的ID。有人知道我该如何解决吗?

这是我关于stackoverflow的第一个问题。

c# .net entity-framework model-view-controller repository-pattern
1个回答
0
投票

您是否将商店定义为产品的外键?这是通过数据注释或通过在Context类中覆盖OnModelCreating来完成的。

可以找到类似的问题here

© www.soinside.com 2019 - 2024. All rights reserved.