我想将 BL 与 DAL 分离。特别是我想保护主键(我不希望我的业务用户修改 Item.Id)。
在我的 DataLayer 中(假设它是一个带有自动生成主键的简单 SQL 表),我尝试插入 item 并更新 item.Id。 我当然不能,因为它是 protected 属性(property)。
有没有办法在不使用反射的情况下做到这一点? (我的意思是也许我的架构是错误的......)
业务层:
public class Item
{
public int Id { get; protected set; }
public string Name { get; set; }
}
public interface IRepository<Item>
{
void Insert(Item item);
//and other CRUD operations
}
DataLayer(将 EntityFramework 与 sqlserver 结合使用):
public class EfRepository : IRepository<Item>
{
EfContext ctx;
public void Insert(Item item)
{
//EfContext uses its ItemEntity, so I have to map Item to EntityItem
var mapped = AutoMapper.Map<Item, EntityItem>(item);
ctx.Items.Add(mapped);
//after this operation EF will set primary key to mapped object
//and now I need to set this to primary key to my business
//domain object.
item.Id = ?? // can't set protected property!!!
}
}
最佳答案
为了保护您的逻辑免受意外修改Id
,您可以使用“属性注入(inject)模式”:
public class Item
{
public Item()
{
_id = -1;
}
public int Id
{
get
{
return _id;
}
set
{
if (_id != -1)
{
throw new OperationException("Item.Id has already been set");
}
_id = value;
}
}
public string Name { get; set; }
}
关于c# - 如何在解耦数据层中设置主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41782578/