Saa*_*nch 5 poco onion-architecture data-annotations entity-framework-5
我正在开发一个遵循洋葱架构的ASP.NET MVC项目.我在我的核心项目中添加了模型,这些模型将被称为基础结构项目中的实体框架模型的POCO类.
我的问题是如何添加依赖于实体框架的数据注释?
我可以将核心模型作为接口并在基础结构项目中继承它并进行实际实现吗?
Max*_*xSC 14
如果从Data Annotations切换到Fluent API,则无需将Core Models创建为接口.
这是一个例子.
该Entity1对象是核心层域对象:
namespace MyApp.Core.Model
{
public class Entity1
{
public short Id { get; set; }
public string ExternalCode { get; set; }
public byte Status { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
在基础结构层中,创建一个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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
你需要做的最后一件事是在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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是IDBContext以防万一:
public interface IDbContext
{
DbSet<T> Set<T>() where T : class;
DbEntityEntry<T> Entry<T>(T entity) where T : class;
int SaveChanges();
void Dispose();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2943 次 |
| 最近记录: |