[entity framework core] Entity Framework Core Model Configuration

https://www.learnentityframeworkcore.com/configuration/fluent-api/model-configuration
https://www.learnentityframeworkcore.com/configuration/fluent-api/ignore-method

Schema

ef core 默认创建 table使用的schema是 dbo, 可以通过下面的方式修改schema:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("MyCustomSchema");
    }

exclude entity

当然你不是想把所有的entity都map到数据库中的表, 可以使用Ignore<TEntity>()的方式:

    public class SampleContext : DbContext
    {
        public DbSet<Contact> Contacts { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Ignore<AuditLog>();
            modelBuilder.Entity<Contact>().Ignore(c => c.FullName);
        }
    }
    public class Contact
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Email { get; set; } 
        public AuditLog AuditLog { get; set; }
        public string FullName => $"{FirstName} {LastName}";
    }
    public class AuditLog
    {
        public int EntityId { get; set; }
        public int UserId { get; set; }
        public DateTime Modified { get; set; }
    }

相似的convention的方式:

    public class Contact
    {
        public int ContactId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; } 
        public AuditLog AuditLog { get; set; }
        [NotMapped]
        public string FullName => $"{FirstName} {LastName}";
    }
    [NotMapped]
    public class AuditLog
    {
        public int EntityId { get; set; }
        public int UserId { get; set; }
        public DateTime Modified { get; set; }
    }
posted @ 2019-10-12 10:38  YanyuWu  阅读(165)  评论(0编辑  收藏  举报