Onion Architecture- Entity Framework Code First Models DataAnnotations

后端 未结 2 1628
无人及你
无人及你 2020-12-15 13:40

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

2条回答
  •  一生所求
    2020-12-15 14:19

    You don't need to create Core Models as Interfaces if you switch from Data Annotations the Fluent API.

    Here's an example.

    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; }
      }
    }
    

    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
      {
         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();
         }
      }
    }
    

    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(null);
          modelBuilder.Configurations.Add(new Configuration.Entity1Mapping());
        }
      }
    }
    

    This is the IDBContext just in case:

    public interface IDbContext
    {
      DbSet Set() where T : class;
      DbEntityEntry Entry(T entity) where T : class;
      int SaveChanges();
      void Dispose();
    }
    

提交回复
热议问题