【发布时间】:2017-07-28 17:08:52
【问题描述】:
我正在使用带有实体框架的 asp.net 样板。 我有 2 个实体:具有多对多关系的产品和供应商。
我的问题:当我保存一个或多个供应商的产品时,供应商产品表上的产品和关系被保存,但供应商记录在供应商表上重复。
我读到这是因为有 2 个来自不同上下文的实体,所以我需要将供应商“附加”到 Products 上下文。我不知道该怎么做。有人可以帮助我吗?
我的实体:
public class Product : FullAuditedEntity
{
public Product()
{
Suppliers = new HashSet<Supplier>();
}
public string Name { get; set; }
public virtual ICollection<Supplier> Suppliers { get; set; }
}
public class Supplier : FullAuditedEntity
{
public Supplier()
{
Products = new HashSet<Product>();
}
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
我的域服务名为 ProductManager
public async Task<Product> Create(Product entity)
{
var product = _repositoryProduct.FirstOrDefault(x => x.Id == entity.Id);
if (product != null)
{
throw new UserFriendlyException("Product already exists.");
}
else
{
return await _repositoryProduct.InsertAsync(entity);
}
}
我的应用服务名为 ProductAppService:
public async Task Create(CreateProductInput input)
{
Product output = Mapper.Map<CreateProductInput, Product>(input);
await _productManager.Create(output);
}
我的 CreateProductInput 数据传输对象
public class CreateProductInput
{
public string Name { get; set; }
public ICollection<Supplier> Suppliers { get; set; }
}
我的角度组件产品列表组件
// GET Products
function getProducts() {
productService.listAll()
.then(function (result) {
vm.users = result.data;
});
}
getProducts();
// GET Suppliers
function getSuppliers() {
supplierService.listAll()
.then(function (result) {
vm.suppliers = result.data;
});
}
getSuppliers();
//Save the data
vm.save = function () {
abp.ui.setBusy();
productService.create(vm.product)
.then(function () {
abp.notify.info(App.localize('SavedSuccessfully'));
$uibModalInstance.close();
}).finally(function () {
abp.ui.clearBusy();
getProducts();
});
}
【问题讨论】:
-
您没有包含最相关的方法实现 -
InsertAsync的Product存储库。 -
这是一个来自 asp.net 样板的方法github.com/aspnetboilerplate/aspnetboilerplate
-
嗯,默认的通用存储库实现非常幼稚,显然不适用于具有相关数据的实体。您很可能需要实现自定义存储库。
-
我想我需要在某处“附加”相关实体。
-
Ivan Stoev,我创建了一个自定义仓库和一个名为 InsertAndAttach 的方法,我在其中手动将实体附加到上下文并解决了问题
标签: c# asp.net asp.net-mvc entity-framework aspnetboilerplate