gpt4 book ai didi

c# - EF NotMapped 和 JsonIgnore 属性导致代码优先问题

转载 作者:行者123 更新时间:2023-11-30 16:57:25 26 4
gpt4 key购买 nike

我有一些模型类用作 Entity Framework 代码优先模型。我在这些模型上有一些不属于数据库模式的属性,为了确保 Entity Framework 不会混淆,我用 [NotMapped] 属性标记了这些属性。当我为模型生成代码优先迁移时,这些属性被正确地忽略了。

但是,我最近向这些相同的属性添加了 [JsonIgnore] 属性,因为模型类正在被反序列化,并且这些属性不适合包含在序列化中。这也可以正常工作 - 但它会产生非常奇怪的结果,即 EF 代码优先迁移无法识别 [NotMapped] 属性。现在我收到 Entity Framework 认为模型类与数据库不同步的错误 - 但是当我生成新的迁移时,它认为它需要为所有以前未映射的属性添加列。从这些属性中删除 [JsonIgnore] 属性可以解决问题。

我看到这个问题以前在 Entity Framework 的上下文之外遇到过,在这个问题中(没有答案):Applying [JsonIgnore] to property causes DataAnnotation attributes to be "lost"

这是 C# 归属系统的一个很好理解的行为吗?还是它特定于 [JsonIgnore] 属性 - 如果是,是什么原因造成的?

最佳答案

尝试使用 [DataContract][DataMember] 属性来定义要序列化的属性。

[DataContract]
public class EntityA
{
[DataMember]
public string SerializeThisProperty { get; set; }

[NotMapped]
public string DoNotSerializeThisProperty { get; set; }
}

关于c# - EF NotMapped 和 JsonIgnore 属性导致代码优先问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26540248/

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