[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()的方式:

    public class SampleContext : DbContext
    {
        public DbSet Contacts { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Ignore();
            modelBuilder.Entity().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; }
    }

你可能感兴趣的:([entity framework core] Entity Framework Core Model Configuration)