如何从 LINQ2SQL 查询中获取可为空的项?
我有一个用于检索 ID(PK,不为空)的 LINQ2SQL 查询。该查询如下:
int masterEntityID;
int payeeID;
int chargePayeeID;
try
{
using (TestDataContext os = new TestDataContext())
{
string entityName = tbSearch.Text;
var getMasterID = from r in os.Entities
where r.Name == entityName
select r.ID;
masterEntityID = getMasterID.First(); //this is working FINE!
var getPayeeID = from pid in os.Entities
where pid.Name == entityName
select pid.Payee_ID;
payeeID = getPayeeID.First(); //This is giving me an err: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
};
ID 和 Payee_ID 两种数据类型均为 int。但 ID 是 Pkey 而 Payee_ID 不是!
如何获取getPayeeID到payeeID的值?谢谢!
I have a LINQ2SQL query for retrieving an ID (PK, not null). Here is that query:
int masterEntityID;
int payeeID;
int chargePayeeID;
try
{
using (TestDataContext os = new TestDataContext())
{
string entityName = tbSearch.Text;
var getMasterID = from r in os.Entities
where r.Name == entityName
select r.ID;
masterEntityID = getMasterID.First(); //this is working FINE!
var getPayeeID = from pid in os.Entities
where pid.Name == entityName
select pid.Payee_ID;
payeeID = getPayeeID.First(); //This is giving me an err: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
};
Both the datatypes: ID and Payee_ID are of int. But ID is Pkey and Payee_ID is Not!
How to get the value from getPayeeID to payeeID? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您确信 Payee_Id 永远不会为空,那么只需转换该值:
If your confident that Payee_Id won't ever be null then just cast the value:
由于值是
int?
,您可以使用Value
属性从中获取int
:int?
是简写对于可为 Nullable
Since the value is
int?
you can get theint
from it using theValue
property:int?
is shorthand forNullable<int>
您可以使用 FirstOrDefault() 或将 payeeID 声明为 int?然后根据需要使用它(如果它为空,你应该尝试做任何事情......)
You can use FirstOrDefault() or declare payeeID as a int? and then use it as you want (if it is null you should try to do anything...)
实体的 Payee_ID 属性似乎可以为空,因为它代表数据库中的可以为空的列。因此,您不应该以不可为 null 的 int 形式接收其值。你可以通过 nullable int 来获取它的值。
或
稍后您可以检查 payeeID 值是否为空或未使用
it seems that Payee_ID property of your entity is nullable that is because it represents a nullable column in the database. so, you should not be receiving its value in int that is not nullable. you can get its value in nullable int like.
or
later you can check if payeeID value was null or not using