如何使用UnitOfWork模式从添加中获取ID? [英] How to get id from Add using UnitOfWork pattern?
问题描述
我正在使用UnitOfWork模式来抽象我的Asp.Net应用程序中的数据库访问。基本上,我遵循此处描述的UnitOfWork模式方法:
I am using the UnitOfWork pattern to abstract database access in my Asp.Net application. Basically I follow the UnitOfWork pattern approach described here:
https://chsakell.com/2015/02/15/asp-net-mvc-solution-architecture-best-practices/
但是,我很难理解如何获得新添加的商品的ID。就像我要向客户存储库中添加新客户一样,我将如何获取客户ID?问题是Add和Commit是分离的,并且在Commit之后才知道ID。
However, I'm struggling to understand, how I will get the Id of a newly added item. Like if I want to add a new customer to my Customer repository, how will I get the customer id? The problem is that Add and Commit are decoupled, and the Id is not known until after Commit.
有没有一种方法可以使用
Is there a way to get the id of an added item, using the UnitOfWork pattern?
推荐答案
请注意,我不希望我的EF模型类传播到我的域层
我已经解决了。我认为它很好用
I have done a workaround. I think it works pretty well
当您需要存储库时,例如 DbCars ,然后插入一个您想要获取仅在 SaveChanges()时生成的 Id 的新 DomainCar 。
When you want a repository, for example of DbCars, and you insert a new DomainCar you want to get that Id that was only generated when SaveChanges() is applied.
public DomainCar //domain class used in my business layers
{
public int Id{get;set;}
public string Name{get;set;}
}
public DbCar //Car class to be used in the persistence layer
{
public int Id{get;set;}
public string Name{get;set;}
public DateTime CreatedDate{get;set;}
public string CreatedBy{get;set;}
}
首先创建通用 IEntity 接口和实现该接口的类:
First you create a generic IEntity interface and a class implementing it:
public interface IEntity<T>
{
T Id { get; }
}
public class Entity<T> : IEntity<T>
{
dynamic Item { get; }
string PropertyName { get; }
public Entity(dynamic element,string propertyName)
{
Item = element;
PropertyName = propertyName;
}
public T Id
{
get
{
return (T)Item.GetType().GetProperty(PropertyName).GetValue(Item, null);
}
}
}
然后在添加方法中存储库中,您返回 Id 类型的 IEntity :
Then in your add method of the repository you return a IEntity of the type of your Id:
public IEntity<int> AddCar(DomainCar car)
{
var carDb=Mapper.Map<DbCar>(car);//automapper from DomainCar to Car (EF model class)
var insertedItem=context.CARS.Add(carDb);
return new Entity<int>(insertedItem,nameof(carDb.Id));
}
然后,在某处调用add方法和随之而来的Save()的工作单位:
Then , somewhere you are calling the add method and the consequent Save() in the UnitofWork:
using (var unit = UnitOfWorkFactory.Create())
{
IEntity<int> item =unit.CarsRepository.AddCar(new DomainCar ("Ferrari"));
unit.Save(); //this will call internally to context.SaveChanges()
int newId= item.Id; //you can extract the recently generated Id
}
这篇关于如何使用UnitOfWork模式从添加中获取ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!