如何返回“指南”来自“可空的Guid”?

发布于 2024-11-01 18:28:20 字数 898 浏览 2 评论 0原文

我正在尝试返回下面的 Guid 值。然而,数据库(和我的 dbml)将该列作为可空 Guid,并且它在 .Select 部分生成异常,表示它可以不能从 IQueryable 转换为 System.Guid

我猜我需要首先使我的返回值“具体”???真的吗?
如果是这样,我该如何使用 Guid 来做到这一点?

public static Guid GetCurrentWorkerByType(int enrollmentID, int staffTypeID)
{
    using (var context = CmoDataContext.Create())
    {
        IQueryable<tblWorkerHistory> tWorkHist = context.GetTable<tblWorkerHistory>();

        return (tWorkHist.Where(workHist => 
            (workHist.EnrollmentID == enrollmentID) &&
            (workHist.tblStaff.StaffTypeID == staffTypeID) &&
            (workHist.EndDate == null || workHist.EndDate > DateTime.Now))
            .Select(workHist => workHist.Worker));
        }
    }
}

I am trying to return a Guid value below. However the database(and my dbml) has that column as a nullable Guid and it is generating an exception on the .Select portion saying it can't convert from an IQueryable<System.Guid?> to a System.Guid.

I am guessing I need to make my return value "concrete" first???? True?
If so how do I do that with Guid's?

public static Guid GetCurrentWorkerByType(int enrollmentID, int staffTypeID)
{
    using (var context = CmoDataContext.Create())
    {
        IQueryable<tblWorkerHistory> tWorkHist = context.GetTable<tblWorkerHistory>();

        return (tWorkHist.Where(workHist => 
            (workHist.EnrollmentID == enrollmentID) &&
            (workHist.tblStaff.StaffTypeID == staffTypeID) &&
            (workHist.EndDate == null || workHist.EndDate > DateTime.Now))
            .Select(workHist => workHist.Worker));
        }
    }
}

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

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

发布评论

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

评论(6

浪菊怪哟 2024-11-08 18:28:20
// Get the Guid? itself, for sake of example from IQueryable<Guid?>
// (could be `null` from DB value or because queryable was empty)
Guid? maybeGuid = queryable.FirstOrDefault();
// Need to have *a* GUID or default it to something
// because a Guid is a value-type and needs *a* value.
Guid theGuid = maybeGuid ?? Guid.Empty;

另请参阅 Nullable.HasValue/Value - 更长但等效的方法是:

Guid theGuid = maybeGuid.HasValue ? maybeGuid.Value : Guid.Empty;     

观察 HasValue 可能适合一般情况 if 语句来更改逻辑,还要注意,如果 MaybeGuid 为“没有值”,则 Value 将抛出异常 - 为 null - 这就是需要防护的原因。

快乐编码。


迂腐的细节:等效方法不是“线程安全”的。也就是说,假设 maybeGuid 被共享,则可以在 HasValueValue 之间为其分配 null。有许多 SO 问题涉及 ?? (合并运算符)的“线程安全”——生成的 IL 有效地使用临时变量,因此该值可能已过时,但异常可以'不要被扔掉。

// Get the Guid? itself, for sake of example from IQueryable<Guid?>
// (could be `null` from DB value or because queryable was empty)
Guid? maybeGuid = queryable.FirstOrDefault();
// Need to have *a* GUID or default it to something
// because a Guid is a value-type and needs *a* value.
Guid theGuid = maybeGuid ?? Guid.Empty;

Also see Nullable<T>.HasValue/Value -- A longer, but equivalent, method would be:

Guid theGuid = maybeGuid.HasValue ? maybeGuid.Value : Guid.Empty;     

Observe that HasValue may be suitable in general if statements to change logic and also note that Value will throw an exception if maybeGuid is "has no value" -- is null -- which is why the guard is required.

Happy coding.


Pedantic detail: The equivalent method is not "thread safe". That is, assuming maybeGuid was shared, it could be assigned null between HasValue and Value. There are a number of SO questions that cover the "thread safety" of ?? (the coalesce operator) -- the generated IL effectively uses a temporary variable so the value may be stale but an exception can't be thrown.

白昼 2024-11-08 18:28:20

使用

.Select(workHist => workHist.Worker).Single();
  • .Select() 返回尚未运行的查询。
  • 如果您使用 .Select().ToList() 那么您将返回一个列表。
  • 如果您使用.Select().Single(),那么您将返回一项,并且它确保只有一项存在(
  • 如果您使用.Select())。 SingleOrDefault() 然后您返回一项和默认项。查询不得包含超过 1 个项目。
  • 如果您使用 .Select().First() 那么您将返回第一项。查询必须至少包含 1 项。
  • 如果您使用.Select().FirstOrDefault(),那么您将返回第一项或默认项。查询可以包含 1 个或多个项目,或者不包含任何项目。

Use

.Select(workHist => workHist.Worker).Single();
  • .Select() returns a query that has not run.
  • If you use .Select().ToList() then you you return a list.
  • If you use .Select().Single() then you return one item and it makes sure only one item is there
  • If you use .Select().SingleOrDefault() then you return one item and default. Query must not contain more than 1 item.
  • If you use .Select().First() then you return the first item. Query must contain at least 1 item.
  • If you use .Select().FirstOrDefault() then you return the first item or default. Query can contain 1 or more or no items.
凡尘雨 2024-11-08 18:28:20

尝试
将返回类型从 System.Guid 更改为 ?System.Guid // nullable of guid
然后在 select 调用后添加 .FirstOrDefault()

结构体不能为 null,但 System.Nullable 类将该结构体包装在类中。

Try
Change your return type from System.Guid to ?System.Guid // nullable of guid
Then add .FirstOrDefault() after the select call

A struct cannot be null, but the System.Nullable class wraps the struct in a class.

却一份温柔 2024-11-08 18:28:20

你所得到的是一个尚未执行的查询,对于一个,对于两个,据我所知,它将返回一个 Guid 列表。如果您想返回第一个 Guid 或默认值(我认为这是一个归零的 guid),您可以在选择后说 .FirstorDefault() 。

What you've got is a query that hasn't executed for one, and for two, it will return a list of Guids as far as I can tell. If you want to return the first Guid or default (which I believe is a zero'd out guid) you can say .FirstorDefault() after your select.

桃气十足 2024-11-08 18:28:20

最接近用 Guid 表示 null 的方法是使用 Guid.Empty。因此,对于您的查询,您可能需要首先选择 FirstOrDefault 返回的值,进行空检查,然后返回一个可解析的值:

Guid? result = tWorkHist.Where(workHist => 
                   (workHist.EnrollmentID == enrollmentID) 
                   && (workHist.tblStaff.StaffTypeID == staffTypeID) 
                   && (workHist.EndDate == null || workHist.EndDate > DateTime.Now))
                   .Select(workHist => workHist.Worker)
                   .FirstOrDefault();

return result.HasValue ? result.Value : Guid.Empty;

The closest you will get representing null with a Guid is to use Guid.Empty. So, for your query, you will probably want to first pick the value returned by FirstOrDefault, make a null check, and then return a reasnable value:

Guid? result = tWorkHist.Where(workHist => 
                   (workHist.EnrollmentID == enrollmentID) 
                   && (workHist.tblStaff.StaffTypeID == staffTypeID) 
                   && (workHist.EndDate == null || workHist.EndDate > DateTime.Now))
                   .Select(workHist => workHist.Worker)
                   .FirstOrDefault();

return result.HasValue ? result.Value : Guid.Empty;
随波逐流 2024-11-08 18:28:20

将 FirstOrDefault 与 Guid.Empty 的 conjunticon 结合使用

试试这个:

public static Guid GetCurrentWorkerByType(int enrollmentID, int staffTypeID)
{
 using (var context = CmoDataContext.Create())
 {
  IQueryable<tblWorkerHistory> tWorkHist = context.GetTable<tblWorkerHistory>();
    var guid = (tWorkHist.Where(workHist => (workHist.EnrollmentID == enrollmentID) && 
                    (workHist.tblStaff.StaffTypeID == staffTypeID) &&(workHist.EndDate == null || workHist.EndDate > DateTime.Now))
        .Select(workHist => workHist.Worker)
     ///####NOTICE THE USE OF FirstOrDefault
        ).FirstOrDefault();
    return (guid.HasValue)?guid.Value:Guid.Empty
    }
}

Use FirstOrDefault with conjunticon with Guid.Empty

Try this:

public static Guid GetCurrentWorkerByType(int enrollmentID, int staffTypeID)
{
 using (var context = CmoDataContext.Create())
 {
  IQueryable<tblWorkerHistory> tWorkHist = context.GetTable<tblWorkerHistory>();
    var guid = (tWorkHist.Where(workHist => (workHist.EnrollmentID == enrollmentID) && 
                    (workHist.tblStaff.StaffTypeID == staffTypeID) &&(workHist.EndDate == null || workHist.EndDate > DateTime.Now))
        .Select(workHist => workHist.Worker)
     ///####NOTICE THE USE OF FirstOrDefault
        ).FirstOrDefault();
    return (guid.HasValue)?guid.Value:Guid.Empty
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文