efcore 实体配置_具有私有设置程序的EFCore基本实体模型属性-迁移异常行为

在使用EFCore时,基类中的私有设置器可能导致迁移异常。例如,多个类(Bar和Baz)继承自Foo,运行Add-Migration命令时,生成的模式可能错误地删除或忽略了`Created`属性。有时,`Created`属性被标记为要删除的列,有时所有`Created`属性都被标记为移除。这可能与EFCore工具处理私有设置器的方式有关,特别是当存在名称相似的其他属性时。解决方案是,只有在特定条件下(如设置别名键)EF Core工具才会映射基类的私有设置器。
摘要由CSDN通过智能技术生成

It seems private setters inside classes that entity models inherit from cause bizarre issues with EFCore migrations. Consider the following example, where there are multiple classes (Bar and Baz) that inherit from Foo. When running Add-Migration commands multiple times (add/remove the private modifier`), the generated schema is just wrong in multiple ways.

Sometimes the Created property is set to be a dropped column

Sometimes all the the Created properties are set to be removed (and not replaced/renamed with anything).

It's my understanding that EFCore tools don't really treat properties with private setters with any special care. Is this a wrong assumption? If so, why do some private setters work on base classes, but not others? I'm assuming this is a bug in the EF Tools, perhaps related to how it treats naming on properties, considering I have other properties with similar names in the model which might be confusing the tools

public class Context : DbContext

{

public DbSet Bars { get; set; }

public DbSet Bazs { get; set; }

}

public class Bar : Foo { }

public class Baz : Foo { }

public abstract class Foo

{

protected Foo()

{

Created = DateTimeOffset.UtcNow;

}

public DateTimeOffset? Created { get; private set; }

public DateTimeOffset? Updated { get; set; }

}

Edit -> It seems private setters for DateTimeOffset cause EF Tools to never map them in base classes. However, I have a string property with a private setter with [Required] and [StringLength] attributes, along with builder.Entity().HasAlternateKey(x => x.RequiredStringProperty); In that case, EF absolutely maps the property...but only with some of the classes that are inheriting from Foo.

解决方案

The EF core tools will map private setters of base classes only under certain conditions.

For example, if you have builder.Entity().HasAlternateKey(x => x.Created);, then EF tools will map the Created property regardless of whether it has a private or public setter.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值