【问题标题】:EF - Conditionally allow saving a property value (which has a backing field)EF - 有条件地允许保存属性值(具有支持字段)
【发布时间】:2019-08-29 18:57:07
【问题描述】:

我有一个 User 实体和一个具有一对一关系的 EmailRecipient 实体。电子邮件收件人也可以在没有相关用户实体的情况下创建。

我的EmailRecipient 实体从User 实体中获取NameSurnameEmailAddress(如果已附加/包含)。我已设置属性以在返回用户属性之前返回支持字段值(如果它不为空),因此我可以根据需要指定替代名称。

保存EmailRecipient 时,EF 会查看NameSurnameEmailAddress 属性,并使用User 实体中的值填充EmailRecipient 表,而不是使用支持字段值。如果我没有明确设置值,我希望这些字段在数据库中保持为 NULL,即recipient.Name = "new name";

我的问题:如何使 EF 根据支持字段值而不是属性值填充选定的数据库字段?还是有完全不同的方法来解决这个问题?

电子邮件收件人实体:

public class EmailRecipient
{
    private string _name;
    public virtual string Name 
    { 
        get { return User == null ? _name : _name ?? User.Name; }
        set { _name = value; }
    }

    private string _surname;
    public virtual string Surname
    {
        get { return User == null ? _surname : _surname ?? User.Surname; }
        set { _surname = value; }
    }

    private string _emailAddress;
    public virtual string EmailAddress
    {
        get { return User == null ? _emailAddress : _emailAddress ?? User.EmailAddress; }
        set { _emailAddress = value; }
    }

    [Key, ForeignKey(nameof(UserId))]
    public User User { get; protected set; }
    public long? UserId { get; set; }
}

【问题讨论】:

    标签: .net-core .net-core-2.2 abp


    【解决方案1】:

    经过进一步的挖掘,我想我已经找到了解决方案。仔细阅读微软的EF Core backing fields文档,似乎我们可以明确要求EF读写backing field而不是使用属性。

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<EmailRecipient>().Property(x => x.Name)
            .UsePropertyAccessMode(PropertyAccessMode.Field);
    }
    

    支持字段保持null,直到设置新的Name,即recipient.Name = "new name";,因此,我可以使用recipient.Name属性返回recipient._name(存储在数据库中)或者如果它是空的,recipient.User.Name

    【讨论】:

      猜你喜欢
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2020-06-22
      • 2013-12-31
      • 1970-01-01
      相关资源
      最近更新 更多