处理 DBNull 的通用方法

发布于 2024-12-14 19:50:55 字数 905 浏览 8 评论 0原文

使用 SqlDataReader 时,我的代码中有很多此类逻辑 有没有更干净、更通用的方法来处理这个问题?

 if (reader["VisitingAddressId"] != DBNull.Value)
 {
     visitingAddress = new Address()
     {
         AddressId = Convert.ToInt64(reader["VisitingAddressId"]),
         Address1 = reader["VisitingAddress"].ToString(),
         AddressType = AddressType.VisitingAddress,
         PostalCode = reader["VisitingPostal"].ToString(),
         PostalDistrict = reader["VisitingPostalDistrict"].ToString()
      };
  }

 if (reader["PostalAddressId"] != DBNull.Value)
 {
     postalAddress = new Address()
     {
         AddressId = Convert.ToInt64(reader["PostalAddressId"]),
         Address1 = reader["PostalAddress"].ToString(),
         AddressType = AddressType.PostalAddress,
         PostalCode = reader["PostalPostal"].ToString(),
         PostalDistrict = reader["PostalPostalDistrict"].ToString()
      };
  }

I have a lot of this type of logic in my code when using the SqlDataReader
Is there a cleaner more generic way to handle this?

 if (reader["VisitingAddressId"] != DBNull.Value)
 {
     visitingAddress = new Address()
     {
         AddressId = Convert.ToInt64(reader["VisitingAddressId"]),
         Address1 = reader["VisitingAddress"].ToString(),
         AddressType = AddressType.VisitingAddress,
         PostalCode = reader["VisitingPostal"].ToString(),
         PostalDistrict = reader["VisitingPostalDistrict"].ToString()
      };
  }

 if (reader["PostalAddressId"] != DBNull.Value)
 {
     postalAddress = new Address()
     {
         AddressId = Convert.ToInt64(reader["PostalAddressId"]),
         Address1 = reader["PostalAddress"].ToString(),
         AddressType = AddressType.PostalAddress,
         PostalCode = reader["PostalPostal"].ToString(),
         PostalDistrict = reader["PostalPostalDistrict"].ToString()
      };
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

始终不够 2024-12-21 19:50:55

我在数据服务类中有这些辅助方法(您可以将它们设为静态):

    public T CastDBValue<T>(object value)
    {
        return MapValue<T>(value);
    }   

    internal static T MapValue<T>(object value)
    {
        try
        {
            T result;
            result = value == DBNull.Value ? default(T) : (T)value;
            return result;
        }
        catch (InvalidCastException cex)
        {
            logger.ErrorFormat("Invalid cast while mapping db value '{0}' to type {1}. Error: {2}", value, typeof(T).Name, cex);
            throw new InvalidCastException(string.Format("Invalid cast while mapping db value '{0}' to type {1}. Error: {2}", value, typeof(T).Name, cex.Message));
        }
    }

然后在映射代码中,您只需执行以下操作:

AddressId = dataService.CastDBValue<int>(reader["AddressId"]));
if (AddressId > 0) { ... }

I have these helper methods in a data service class (you could make them both static):

    public T CastDBValue<T>(object value)
    {
        return MapValue<T>(value);
    }   

    internal static T MapValue<T>(object value)
    {
        try
        {
            T result;
            result = value == DBNull.Value ? default(T) : (T)value;
            return result;
        }
        catch (InvalidCastException cex)
        {
            logger.ErrorFormat("Invalid cast while mapping db value '{0}' to type {1}. Error: {2}", value, typeof(T).Name, cex);
            throw new InvalidCastException(string.Format("Invalid cast while mapping db value '{0}' to type {1}. Error: {2}", value, typeof(T).Name, cex.Message));
        }
    }

Then in your mapping code, you just do:

AddressId = dataService.CastDBValue<int>(reader["AddressId"]));
if (AddressId > 0) { ... }
猫瑾少女 2024-12-21 19:50:55

您可以使用像 Dapper 这样的微型 ORM:http://code.google.com/ p/dapper-dot-net/

多重映射功能将消除所有样板代码。

db.Query<Post,Address,Address,Post>("select * from Posts left join Address ... etc", 
 (post,vaddress,paddress) => 
  {
     post.VisitingAddress = vaddress; 
     post.PostalAddress = paddress; 
     return post; 
   });

You could use a micro-ORM like Dapper: http://code.google.com/p/dapper-dot-net/

The multi mapping functionality would eliminate all that boiler plate code.

db.Query<Post,Address,Address,Post>("select * from Posts left join Address ... etc", 
 (post,vaddress,paddress) => 
  {
     post.VisitingAddress = vaddress; 
     post.PostalAddress = paddress; 
     return post; 
   });
裂开嘴轻声笑有多痛 2024-12-21 19:50:55

你指的是ORM,ORM有很多。 NHibernate、实体框架,甚至 ADO.NET(您已经在使用)都支持关系数据集,尽管在这种情况下您通常必须使用 DataSet 或派生的强类型类。

查看此处的 .NET 部分以获取列表:

http://en.wikipedia.org/wiki/ List_of_object-relational_mapping_software

您有什么要求?也许我们可以缩小范围。

What you are referring to are ORMs, of which there are many. NHibernate, Entity Framework, even ADO.NET (which you are already using) has support for relational datasets, although in that case you usually have to use a DataSet or derived, strongly-typed classes.

Check out the .NET section here for a list:

http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software

What are you requirements? Maybe we can narrow it down.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文