gpt4 book ai didi

c# - EF Core 支持字段 - 将属性公开为另一种类型?

转载 作者:太空狗 更新时间:2023-10-29 21:16:13 24 4
gpt4 key购买 nike

假设我有一个 EF 实体类 Person,上面有一个 PhoneNumber。 PhoneNumber 存储为字符串类型,但我希望对 Person 的所有访问都通过具有一些不错的访问器函数的 Phone,例如验证或 GetAreaCode()。我想在数据库中将其作为字符串备份,但在查询时我想将其作为电话号码返回:

public class Person {
public PhoneNumber Phone { /* Some clever get/set logic here */ }

private string _phoneNumber; // Backing field
}

或者我可以让 PhoneNumber 将其自身存储为字符串吗?如果我只是通过删除上面的支持字段将其包含在模型中,EF 会被构造函数(一个 protected 构造函数,其参数比一个字符串更多)以及一个复制构造函数 PhoneNumber(PhoneNumber other)。我可以让 EF 以某种方式忽略那些吗?

我对想法持开放态度...

最佳答案

您可以使用@nbrosz 的answer来解决您的问题,但如果您使用的是 EF Core 2.1,则不再需要执行此类解决方法。您可以使用 EF Core 2.1(自 2018 年 5 月 7 日起在 Release Candidate 1 中)删除支持字段,您可以使用值转换功能解释 here由微软:

Value converters allow property values to be converted when reading from or writing to the database. This conversion can be from one value to another of the same type (for example, encrypting strings) or from a value of one type to a value of another type (for example, converting enum values to and from strings in the database.)

因此对于您的情况,您可以删除支持字段。你不再需要它了。你的类应该是这样的:

public class Person 
{
public PhoneNumber Phone { /* Some clever get/set logic here */ }
}

在你的OnModelCreating方法,您可以像下面这样配置转换:

modelBuilder.Entity<Person>()
.Property(p => p.Phone)
.HasConversion(
phone => {
// Here you code the logic of how to get the value to store in DB
return ...;
},
dbValue => {
// Here you code the logic of how to construct the PhoneNumber instance from the value to store in DB
}
);

就是这样。实际上它在候选版本中,但微软说:

EF Core 2.1 RC1 is a “go live” release, which means once you test that your application works correctly with RC1, you can use it in production and obtain support from Microsoft, but you should still update to the final stable release once it’s available.

我回答的其余部分是针对 @nbrosz 的,因为您正在处理枚举类型。您可以删除支持字段,也可以删除 EF Core 2.1 提供的众多内置值转换器之一。对于枚举到字符串值的转换,我们有类型 EnumToStringConverter .对于您在回答中所做的逻辑,您可以将其简化为实体:

[Display(Name = "Fire Type")]
public Enums.FireType Type { get; set; }

我们删除了 NotMapped属性上的属性,没有用于转换的逻辑 y。

在你的OnModelCreating你这样做的方法:

var converter = new EnumToStringConverter<FireType>();

modelBuilder
.Entity<Fire>()
.Property(e => e.FireType)
.HasConversion(converter);

您还可以让 EF Core 通过使用 HasConversion<T> 的通用版本为您检测正确的转换器如下所示:

modelBuilder
.Entity<Fire>()
.Property(e => e.FireType)
.HasConversion<string>();

如果你不喜欢使用流畅的配置,你可以使用 Column如下所示的数据注释属性,EF Core 将为您进行转换:

[Column(TypeName = "nvarchar(20)")]
[Display(Name = "Fire Type")]
public Enums.FireType Type { get; set; }

关于c# - EF Core 支持字段 - 将属性公开为另一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49193292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com