EntityFramework 实体封装

问题描述 投票:0回答:1

在 c# EF Core 中,确实存在实体属性使用私有设置器或公共设置器的任何模式或建议。我都尝试了,我认为选项 2 更适合验证。 我应该两者都用吗,取决于具体情况?

Option 1:
public class GeoCityEntity {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public DateTime? UpdatedAt { get; set; }
}


Option 2:
public class GeoCityEntity {
    public int Id { get; private set; }
    public string Name { get; private set; }
    public string Code { get; private set; }
    public DateTime? UpdatedAt { get; private set; }

    private GeoCityEntity() {}

    public GeoCityEntity(string name, string code) {
        Name = name;
        Code = code;
    }

    public void Update(string name, string code) {
        Name = name;
        Code = code;
        UpdateAt = DateTime.Now;
    }

    public void UpdateOnlySomeProps(string name) {
        Name = name;
        UpdateAt = DateTime.Now;
    }
}
c# entity-framework-core encapsulation ef-core-2.0
1个回答
0
投票

解决这个问题我最喜欢的方法是:包装模型类。加载您的实体(启用跟踪),从中创建模型,通过模型方法更新实体并在您的上下文中调用保存。

public class GeoCityModel
{
    private readonly GeoCityEntity _entity;

    private GeoCityModel(GeoCityEntity entity)
    {
        _entity = entity;
    }

    public static GeoCityModel Init(GeoCityEntity entity) => new(entity);

    public static GeoCityModel Create(string name, string code)
    {
        return new(new GeoCityEntity() { Code = code, Name = name });
    }

    public void Update(string name, string code) {
        _entity.Name = name;
        _entity.Code = code;
        _entity.UpdatedAt = DateTime.Now;
    }

    public void UpdateOnlySomeProps(string name) {
        _entity.Name = name;
        _entity.UpdatedAt = DateTime.Now;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.