c# - 如何在解耦数据层中设置主键

标签 c# n-tier-architecture

我想将 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/

相关文章:

c# - 如何通过MySqlReader C#读取多个请求

architecture - 将 N 层应用程序重建为面向服务的架构 (SOA)?

architecture - 在 ntier 应用程序中传递数据

asp.net-mvc - 在应用 SOLID 原则时需要帮助

c# - 从字符串中删除字母

c# - StreamReader 文件如何仅在列表框中达到高分时更新?

wpf - 三层架构中的 MVVM WPF 应用程序

c# - 如何在 C# (mono) 中使用 Gdk# 库?

c# - ReSharper/C# 中的 "Delegate subtraction has unpredictable result"?