我正在开发一个遵循 Onion 架构的 ASP.NET MVC 项目。我已经在我的核心项目中添加了模型,这些模型将被称为基础设施项目中实体框架模型的 POCO 类。
我的问题是如何添加取决于实体框架的数据注释?
我可以将核心模型作为接口并在基础设施项目中继承并进行实际实施吗?
我正在开发一个遵循 Onion 架构的 ASP.NET MVC 项目。我已经在我的核心项目中添加了模型,这些模型将被称为基础设施项目中实体框架模型的 POCO 类。
我的问题是如何添加取决于实体框架的数据注释?
我可以将核心模型作为接口并在基础设施项目中继承并进行实际实施吗?
如果您从数据注释切换到 Fluent API,则无需将核心模型创建为接口。
这是一个例子。
该Entity1对象是核心层领域对象:
namespace MyApp.Core.Model
{
  public class Entity1
  {
    public short Id { get; set; }
    public string ExternalCode { get; set; }
    public byte Status { get; set; }
  }
}
在基础设施层中,创建一个Entity1Mapping类,您将在其中执行使用 Data Annotation 所做的事情,但这次使用 Fluent API 代替:
using System.Data.Entity.ModelConfiguration;
namespace MyApp.Infrasrtucture.Data.Configuration
{
  internal class Entity1Mapping : EntityTypeConfiguration<Core.Model.Entity1>
  {
     internal Entity1Mapping()
     {
       HasKey(g => g.Id);
       Property(g => g.Id).IsRequired();
       Property(g => g.ExternalCode)
           .IsRequired()
           .HasMaxLength(100)
           .IsVariableLength()
           .IsUnicode(false);
       Property(g => g.Status).HasColumnName("EntityStatus").IsRequired();
     }
  }
}
您要做的最后一件事是在modelBuilder您的上下文中添加映射:
using System.Data.Entity;
namespace MyApp.Infrastructure.Data
{
  public class MyContext : DbContext, IDbContext
  {
    public MyContext() : base("ConnectionStringMyContext")
    { }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      Database.SetInitializer<MyContext>(null);
      modelBuilder.Configurations.Add(new Configuration.Entity1Mapping());
    }
  }
}
这是 IDBContext 以防万一:
public interface IDbContext
{
  DbSet<T> Set<T>() where T : class;
  DbEntityEntry<T> Entry<T>(T entity) where T : class;
  int SaveChanges();
  void Dispose();
}
    在我看来,使用 FluentAPI 是一个很好的解决方案。
值得注意的是 System.Component.DataAnnotations 不依赖于 EntityFramework - 因此您可以在核心项目中使用 DataAnnotations 并且仍然不知道您的特定持久性机制。