最佳实践–在与实体主键相对应的类属性上使用Nullable数据类型 [英] Best practices – using Nullable data types on class properties that correspond to entities primary keys

查看:94
本文介绍了最佳实践–在与实体主键相对应的类属性上使用Nullable数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个图书馆:

  • 旨在与数据访问层进行通信的业务对象.每个类都有一个属性(类型为long),该属性与数据库实体的主键相对应.

  • Business objects designed to communicate with the Data Access Layer.  Every class has a property (of type long) that corresponds to the primary key of the database entity. 

中间层业务逻辑层,它将那些业务对象传达回DAL

A middle tier business logic layer that will communicate those business objects back to the DAL

与UI进行通信的数据传输对象(DTO)库.在查看,更新或删除之前,业务逻辑层会验证DTO上的主键属性是否为零值.

A Data Transfer Objects (DTOs) library that communicates to the UI.  The business logic layer validates the primary key property on the DTOs for zero values prior to viewing or updating or deleting. 

一位程序员(对数据库开发有更丰富的经验)抱怨这等效于"NULL不为零".他希望将所有DTO上的ID更改为Nullable,但将ID保留在业务对象(与 DAL).另一位程序员认为,针对零对主键进行验证是有效的,因为对于任何实体,零都不是有效的主键.

One programmer (who is more experienced with Database development) complains that this is equivalent to "NULL is not zero".  He wants the Ids on all of the DTOs to be changed to Nullable but leave the Ids on the business objects (that communicate to the DAL) as long.  Another programmer thinks that validating against zeros for primary key is valid because zero is not a valid primary key for any entity.

"NULL不为零"参数是否适用于这种情况?这是最佳做法"吗?

Does the "NULL is not zero" argument apply to this scenario?  Is it a "best practice" that all Ids on the DTOs be converted to Nullable but passed as long to the business objects after being validated for not being null?

推荐答案

C语言中的null最初定义为-1,这可以追溯到C的发展.在开发C#时,null成为对象,并且会发出警告,提示您需要将对象类型转换为整数.这不是一个好习惯 可以将-1用作null.

null in C language was originally definjed a -1 going back to the developement of C.  When C# was developed null became an object and you would ge t a warning the your needed to type cast the object to an integer.  It is not a good practice any more to use -1 for null.

我认为这两种方法都不对还是错.您基本上需要一种确定何时没有数据从数据库返回的方法.如果数据库返回的是整数(主键-行号),则使用0或-1是等效的.如果 您使用-1,则需要使用有符号整数,并且由于所有行号均为正数,因此会丢失可能行的一半范围(所有负数).如果使用零,则可以将返回值声明为无符号整数并增加 您可以将行范围扩大2倍.如果您的函数返回的是对象(不是行号),则需要使用null.

I don't think either approach is right or wrong.  You basiclally need a way of determing when no data gets returned from the database.  If the database is returning an integer (primary key - row number) then using 0 or -1 is equivalent.  if you use -1 then you need to use a signed integer and since all the row number are positive numbers you loose half the range (all the negative numbers) of possible rows.  If you use zero you can declare the return value a unsigned integer and increase you possible range of rows by 2x.  If your function is returning an object (not a row number) than you need to use null.

 


这篇关于最佳实践–在与实体主键相对应的类属性上使用Nullable数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆