更新:
请注意,我知道我不能这样做......这是我真正希望能够发挥作用的。也许还有其他方法可以分离责任,不是吗?所以我正在寻找的是......
实体框架强制将多种职责放入类中(常规逻辑、基本注释和 CRUD 接口功能)。我只想将通常都在一个类中的内容...并通过实体框架和常规逻辑分离类的持久能力。
我的思考过程:最近我开始接触实体框架,但不喜欢某些实体类做得太多的想法。逻辑、数据访问接口和实体框架注释。为了解决这个问题,我想使我的实体类文件部分化,并远离类的其他方面来实现数据访问功能。这个效果很好而且非常干净!
当我这样做时,我认为使我的属性部分化并且使实现远离 EF 属性注释将非常有益!这将清理文件并允许单一责任。然而,这是不允许的!真糟糕。
部分属性将像部分方法一样实现。一个部分属性中的定义,以及另一部分属性中的实现......就像顶部链接中的照片建议(或注释)以及下面的代码一样。
public partial class Agency : PropertyValidator, IAgency
{
private string _name;
public partial string Name
{
get { return _name; }
set
{
// PropertyValidator stuff
if (string.IsNullOrEmpty(value))
AddErrorToProperty("Agency name must contain a reasonable alphanumeric value.");
if (string.IsNullOrWhiteSpace(value))
AddErrorToProperty("Agency name cannot contain all spaces.");
SetPropertyIfValid(ref _name, value);
}
}
}
然后是另一个处理所有抽象数据库项的部分类......
public partial class Agency : IPersitentEntity, IAgency
{
[Key] // NOTE these Annotations are because of Entity Framework...nice separation!
public int ID { get; set; } // From IPersitentEntity
[Required]
[MinLength(3), MaxLength(50)]
public partial string Name { get; set; } // IAgency NOTE this is not valid, but the
// separation is amazing!
// From IPersitentEntity provide CRUD support
public void Create() { throw new NotImplementedException(); }
public void Retrieve(int id) { throw new NotImplementedException(); }
public void Update(int id) { throw new NotImplementedException(); }
public void Delete(int id) { throw new NotImplementedException(); }
}
现在,我必须将注释和逻辑结合在一起。这有点奇怪,因为我已经分离出了抽象数据库项目......除了 EF 注释!