c# - {"error":"Explicit construction of entity type ' ## #' in query is not allowed."}

标签 c# entity-framework linq api

我是 LINQ 的新手,我收到此错误消息:

{"error":"Explicit construction of entity type 'Proj.Models.Ad' in query is not allowed."}

我正在使用这段代码来检索数据

public ActionResult favads()
{
    bool isValid = false;
    string authToken = "";
    if (Request["dt"] != null)
        authToken = Request["dt"].ToString().Trim();
    else
        return Content("{\"error\":\"Please send device token parameter 'dt'.\"}", "application/json");

    string message = (new CommonFunction()).ValidateToken(authToken, out isValid);

    if (isValid)
    {
        long userID = 0;
        if (Request["userID"] != null)
            long.TryParse(Request["userID"].ToString().Trim(), out userID);
        else
            return Content("{\"error\":\"Please send user id parameter 'userID'.\"}", "application/json");

        if (userID < 1)
            return Content("{\"error\":\"Please select appropriate user to view details.\"}", "application/json");

        try
        {
                var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) && Favtb.StatusID.Equals(1)).Select(p => new Ad() { ID = p.AdID.Value, CategoryID = int.Parse(p.CategoryID.ToString()) })
                    from c in db.Ads.Where(Adstb => Adstb.ID == d.ID).DefaultIfEmpty()
                    select new
                    {
                        FavId = d.ID,
                        c.ID,
                        c.Category.ParentCategoryID,
                        c.Category.CategoryID,
                        c.Category.LogoFile,
                        c.Category.CatName,
                        c.AdTitle,
                        AdDescription = (c.AdDescription.Length > 50 ? c.AdDescription.Substring(0, 50) : c.AdDescription),
                        c.CityID,
                        c.Price,
                        c.CreationDate,
                        c.Photos,
                        c.VideoUrl,
                        c.IsMobileVisibile
                    };

            int pg = 0;
            if (Request["p"] != null)
                int.TryParse(Request["p"], out pg);

            string _sortby = "MRF";
            if (Request["sortby"] != null)
                _sortby = Request["sortby"];

            if (_sortby.Equals("OF"))
                q = q.OrderBy(ad => ad.CreationDate.Value);
            else if (_sortby.Equals("PD"))
                q = q.OrderByDescending(ad => ad.Price.Value);
            else if (_sortby.Equals("PA"))
                q = q.OrderBy(ad => ad.Price.Value);
            else
                q = q.OrderByDescending(ad => ad.CreationDate.Value);

            return Json(q.ToList().Skip(pg * recordsPerPage).Take(recordsPerPage), JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Content("{\"error\":\"" + ex.Message + "\"}", "application/json");
        }
    }
    else
    {
        return Content("{\"error\":\"" + message + "\"}", "application/json");
    }
}

广告类

public class Ads : Ad
{
    public long ID { get; set; }
    public string FashionType { get; set; }
    public string ForRentSale { get; set; }
    public string ForJobHire { get; set; }
    public string JobTypeID { get; set; }
}

最佳答案

Ad 也被映射,您不能像这样在查询中投影它的新实例。参见 this question .

你可以做的只是创建一个匿名类型,在这种情况下甚至更好,因为在你的查询中你只使用 Ad 对象的 ID 检索:

var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) && 
                                                  Favtb.StatusID.Equals(1))
                                  .Select(p => p.AdID.Value)
        from c in db.Ads.Where(Adstb => Adstb.ID == d).DefaultIfEmpty()
        select new
        {
            FavId = d,
            c.ID,
            c.Category.ParentCategoryID,
            /* ... */
        };

我建议您查看导航属性。我认为这会让这个查询看起来更整洁

也可以看看这个选项而不是对第一个表使用方法语法,可能更具可读性:

var q = from d in db.AdsFavourites
        //In this case also no need for `Equals` - you are comparing value types
        where d.CreateBy == userID && d.StatusID == 1

        from c in db.Ads.Where(Adstb => Adstb.ID == d.AdID.Value).DefaultIfEmpty()
        select new
        {
            FavId = d.AdID.Value,
            c.ID,
            /* ... */
        };

关于c# - {"error":"Explicit construction of entity type ' ## #' in query is not allowed."},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43154759/

相关文章:

c# - 单击下一步转到第一个选项卡时,ASP.NET C# datagridview 在第二个选项卡内分页

c# - 如何更改运行时应用程序设置

c# - 为什么 WPF 使用 HTML/HEX 颜色?

c# - 基于linq查询获取数据库值

c# - 使用附加子句更新实体

entity-framework - EF 的 DbContext 是否应该包含所有表?

.net - LINQ to SQL 左外连接

c# - 从一个通用方法传递对象,其中 T : MyClass to another where T : DerivedClass

c# - LINQ 根据与子元素的匹配返回元素

asp.net - 具有相同键的项目已被添加