【问题标题】:Linq to entity error unable to create constant valueLinq to entity 错误无法创建常量值
【发布时间】:2013-01-26 20:54:20
【问题描述】:

我有一个函数,我向其传递一个字符串,然后使用 linq to entity 检查我传递的字符串值是否已存在于数据库中。为此,我编写了这个函数。

    public static bool UserExistChk(String StrUserId) {
            using (SBVEntities dbcontx = new SBVEntities())
           {
                return dbcontx.Users.Contains(dbcontx.Users.FirstOrDefault(e => e.UserID == StrUserId));

           }
    }

但我收到错误 - 无法创建类型为“MySBVApp.Models.User”的常量值。此上下文仅支持原始类型(“例如 Int32、String 和 Guid”)。

请帮助我是实体框架和 linq 的新手。

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    您可以为此使用Any 扩展方法:

    public static bool UserExistChk(String StrUserId)
    {
      using ( SBVEntities db = new SBVEntities() )
      {
        return db.Users.Any( o => o.UserID == StrUserId );
      }
    }
    

    【讨论】:

    • 是的,这就是我要找的东西。非常感谢 Nicholas Butler。
    • @Yagnesh.Dixit 不客气 :) 有一些示例可以帮助您了解 LINQ to Objects 和 LINQ to Entities - google "101 LINQ samples"
    【解决方案2】:

    你可以使用:

    public static bool UserExistChk(String StrUserId) 
    {
        using (SBVEntities dbcontx = new SBVEntities())
        {
            var query = from u in dbcontx.Users
                        where u.UserId.Contains(strUserId)
                        select u;
        }
        Return query.Count > 0
    }
    

    【讨论】:

      【解决方案3】:

      应该是这样的。

                 using (SBVEntities dbcontx = new SBVEntities())
                 {
                    return (dbcontx.Users
                                   .FirstOrDefault(e => e.UserID == StrUserId) != null 
                                   ? true : false); 
                 }
      

      【讨论】:

      • 感谢 spajce 但它不返回 bool 值我必须检查 null 然后相应地返回一个 bool 值。
      • 非常感谢 spajce,但我正在寻找类似 contains 的东西,它会重新运行 bool 值。 (简而言之,我试图避免您编辑的这个额外代码。)无论如何它工作并解决了我的问题再次感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多