我想將BL從DAL解耦。特別是我想要主鍵保護(我不希望我的業務用戶修改Item.Id)。如何在解耦數據層中設置主鍵
在我的數據層(讓我們想象它是自動生成的主鍵的簡單的SQL表),我嘗試插入項目和更新item.Id. 當然,我不能因爲它是受保護的財產。
有沒有辦法做到這一點,而不使用反射? (我的意思是,也許我的架構是錯誤的...)
BusinessLayer:
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
}
數據層(使用的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!!!
}
}
您正在使用的數據庫? –
,如果你使用的是SQL服務器,那麼你可以把它放在塊本身不需要做任何更多的 –
創建表測試 ( ID INT標識(1,1)主鍵, 名稱爲varchar(100) ) –