配置不同类型的后备字段

问题描述 投票:0回答:1
        private int _billAccount;
        public string BillAccount { get
            {
                var account = _billAccount.ToString().PadLeft(9, '0');
                return account.Substring(0, 3) + "-" + account.Substring(3, 3) + "-" + account.Substring(6, 3);
            }
            set
            {
                var account = new string(value.Where(char.IsDigit).ToArray());
                _billAccount = Convert.ToInt32(account);
            }
        }

类中的BillAccount属性将字符串表示形式处理为(999-999-999)。表中的列定义为

BillAccount INT NOT NULL

我尝试使用

.HasField("_billAccount")
.HasConversion(new NumberToStringConverter<int>())

以及我能想到的任何其他组合,但我无法使其正常工作。

System.InvalidOperationException:指定的字段'_billAccount'类型'int'不能用于以下属性的'Lead.BillAccount'输入“字符串”。仅可从中分配的类型的后备字段可以使用属性类型]

我如何在EF Core 3的Fluent API中进行配置,因此即使字段_billAccount具有不同的类型,它们也都映射到表列BillAccount

c# entity-framework-core fluent
1个回答
0
投票

如@madreflection所指:

public class TheModel {

    private int _billAccount;
    private string _formattedBillAccount = string.Empty;
    public int BillAccount {
        get { return _billAccount; }
        set { 
            _billAccount = value;  
            _formattedBillAccount = value.ToString().PadLeft(9, '0');
            _formattedBillAccount = $"{_formattedBillAccount.Substring(0, 3)}-{_formattedBillAccount.Substring(3, 3)}-{_formattedBillAccount.Substring(6, 3)}";
        }
    }

    [NotMapped]
    public string FormattedBillAccount { get { return _formattedBillAccount; } }
}
© www.soinside.com 2019 - 2024. All rights reserved.