EF Core Fluent API设置接口的所有列类型

编程入门 行业动态 更新时间:2024-10-22 14:04:15
本文介绍了EF Core Fluent API设置接口的所有列类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

不幸的是,ef内核不支持TPC模式,但是我们需要这种行为。我编写了一个称为IBase的接口,每个实体都实现了该接口:

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

我想摆脱注解以使用Fluent API配置。但是我有大约20个不同的实体和7个基值,我不想一遍又一遍地进行相同的配置:

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

有什么想法可以为所有实施IBase的实体配置一次基本属性吗?

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

推荐答案

EF核心可以很好地与基类/继承结合使用,因此只需创建一个基类,然后将通用的东西放入其中,然后从中继承您的模型像这样的基类:

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 }

如果使用fluentapi对您来说至关重要,那么存在一个名为 IEntityTypeConfiguration< TModel>的配置接口; ,您所需要的只是再次创建基本配置,然后从中继承特定配置。然后在您的 DbContext.OnModelCreating 方法中应用这些配置,如下所示:

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

更多推荐

EF Core Fluent API设置接口的所有列类型

本文发布于:2023-11-17 04:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608871.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   类型   Core   EF   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!