Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

c# - Ef core fluent api set all column types of interface

Unfortunately ef core does not support TPC-pattern, but we need this kind of behaviour. I′ve wrote an interface which is called IBase and each entity implements this interface:

public interface IBase
{
    Guid Id { get; set; }

    [Column(TypeName = "datetime2")]
    DateTime CreateDate { get; set; }

    [Required]
    [StringLength(255)]
    string CreateUser { get; set; }

    bool Deleted { get; set; }
}

I want to get rid of Annotations to use the Fluent API configuration instead. But I have about 20 different entities and 7 Base-Values and I don′t want to make the same configuration over and over again:

 modelBuilder.Entity<SomeEntity>()
            .Property(e => e.CreateDate)
            .HasColumnType("datetime2(2)")
            .IsRequired();

Any ideas how to configure each Base-Property once for all entities implementing IBase?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EF core perfectly fine with base classes/inheritance, so just create an base generic class and put common things into it and then inherit your models from those base class like that:

public abstract class BaseModel<TId>
{
    TId Id { get; set; }

    [Column(TypeName = "datetime2")]
    DateTime CreateDate { get; set; }

    [Required]
    [StringLength(255)]
    string CreateUser { get; set; }

    bool Deleted { get; set; }
}

class Model : BaseModel<Guid>{ ... //model specific stuff }

If for some reason it's deadly important for you to use fluentapi than there is a configuration interface exists called IEntityTypeConfiguration<TModel> and all what you need is again create base configuration and latter inherit specific configurations from it. And after that apply those configurations in your DbContext.OnModelCreating method somewhat like that:

class BaseConfiguration<TBaseModel> : IEntityTypeConfiguration<TBaseModel>
{
    public virtual void Configure(EntityTypeBuilder<TBaseModel> builder)
    {
        builder.Property...
    }
}

class ModelConfiguration : BaseConfiguration<Model>
{
    public override void Configure(EntityTypeBuilder<Model> builder)
    {
         base.Configure(builder)
         ...// model specific stuff
    }
}

class CustomDbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfiguration(new ModelConfiguration());
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...