仅当存在于数据库中时才为对象设置属性

Setting properties for object only when present in database

我有一个对象应该用这些值来描述一些客户:

{
    public class CustomerDescription
    {
        public string FirstName { get; set; } = "";
        public string LastName { get; set; } = "";
        public string StreetName { get; set; } = "";
        public string HouseNumber { get; set; } = "";
        public string PostalPlace { get; set; } = "";
        public string PostCode { get; set; } = "";
        public string CountryCode { get; set; } = "";
        public string EMail { get; set; } = "";
        public string PhoneNumber { get; set; } = "";
    }
}

这些值是从客户数据库中检索的,将用于创建一个 XML 文件,该文件将通过 SOAP 发送到另一个数据库。然而,并非所有这些值都始终存在。例如,一位客户可能在数据库中没有国家代码。在这种情况下,我不想在我发送的 XML 文件中包含这个值。这是我如何创建 XML 元素的示例:

new XElement("address",
           new XElement("address1", CustomerDescription.StreetName + " " + cabCustomerDescription.HouseNumber),
           new XElement("postalCode", cUstomerDescription.PostCode),
           new XElement("city", customerDescription.PostalPlace),
           new XElement("countryCode", customerDescription.CountryCode))
)

这是为 CustomerDescription 中的所有属性完成的。我的问题是,如果数据库中不存在某个值,我该怎么做才能使该值不包含在 XML 文件中?我不希望它像 <countryCode></countryCode> 那样是空的,而是根本不存在。

如果数据库中的值为 null,但不包含在 x 元素中,您只需要使用三元运算符。

例如:明确地我将 StreetName 设置为 null 并检查是否为 null 然后不添加到 xml 文件中。

CustomerDescription t = new CustomerDescription();
 t.StreetName = null;
            var abc = new XElement("address", t.StreetName != null ? new XElement("address1", t.StreetName + " " + t.HouseNumber) : null,
            new XElement("postalCode", t.PostCode),
            new XElement("city", t.PostalPlace),
            new XElement("countryCode", t.CountryCode));