当前位置 : 主页 > 网页制作 > HTTP/TCP >

[entity framework core] Entity Framework Core Model Configuration

来源:互联网 收集:自由互联 发布时间:2021-06-16
https://www.learnentityframeworkcore.com/configuration/fluent-api/model-configuration https://www.learnentityframeworkcore.com/configuration/fluent-api/ignore-method Schema ef core 默认创建 table使用的schema是 dbo, 可以通过下面的

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; }
    }
网友评论