洋葱架构-实体框架代码优先模型数据注释 [英] Onion Architecture- Entity Framework Code First Models DataAnnotations
问题描述
我正在按照洋葱体系结构开发一个ASP.NET MVC项目.我已经在核心项目中添加了这些模型,这些模型将被称为基础结构项目中的实体框架模型的POCO类.
I am developing a ASP.NET MVC Project following the Onion Architecture. I have added the Models inside my Core Project and these Models will be referred as the POCO classes for the Entity Framework Models in the Infrastructure Project.
我的问题是如何添加取决于实体框架的数据注释?
My question is how can I add Data Annotations Which depends on the Entity Framework?
我可以将核心模型作为接口并在基础结构项目中继承它并进行真正的实现吗?
Can I make the Core Models as Interfaces and inherit it in the Infrastructure Projects and do real Implementation?
推荐答案
如果您从Fluent API的数据注释"中切换,则无需将核心模型创建为接口.
You don't need to create Core Models as Interfaces if you switch from Data Annotations the Fluent API.
这是一个例子.
Entity1
对象是核心层域对象:
The Entity1
object is a core layer domain object:
namespace MyApp.Core.Model
{
public class Entity1
{
public short Id { get; set; }
public string ExternalCode { get; set; }
public byte Status { get; set; }
}
}
在基础结构层中,创建一个Entity1Mapping
类,您将在其中使用数据注释来完成操作,但是这次使用Fluent API代替:
In the infrastructure layer, create an Entity1Mapping
class where you'll do what you'd have done using Data Annotation, but this time, with the Fluent API instead:
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
中添加映射:
Last thing you have to do, is adding the mapping in the modelBuilder
of your context:
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,以防万一:
This is the IDBContext just in case:
public interface IDbContext
{
DbSet<T> Set<T>() where T : class;
DbEntityEntry<T> Entry<T>(T entity) where T : class;
int SaveChanges();
void Dispose();
}
这篇关于洋葱架构-实体框架代码优先模型数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!