映射无法正常工作 (ASP.NET)

Mapping not working correctly (ASP.NET)

我需要获取所有与人相关的提案

我在数据库中有几个 table。它是 AspNetUsers、UserToRegion、Region、Cities、Projects 和提案。

这是

的模型
AspNetUsers

https://pastebin.com/xts1Xh8m

它与 table UserToRegions

的地区相连

这是型号

https://pastebin.com/8PnBuqf1

所以一个区域可以有多个用户

这里是Region Model

https://pastebin.com/9GS9Qst7

城市与地区相关

所以这是 City

的模型

https://pastebin.com/VWjT0V9h

以及与城市相关的项目

这里是Project模型

https://pastebin.com/ziE3Sb9C

我尝试获取项目和提案的数据(与项目相关的提案)

在控制器上点赞

 public JsonResult Index(string email)
    {
        var id = db.AspNetUsers.Where(x=> x.Email == email).FirstOrDefault();

        string id_val = id.Id;




        var proposals = db.UserToRegions.Where(x=> x.User_Id == id_val)
            .Include(u => u.AspNetUser).Include(u => u.Region).Include(u=>u.Region.Cities)
            .Select(x=> new {
                 Project = x.Region.Cities.,
                 WorkTime = x.WorkTime,
                 Quantity = x.Quantity,
                 Price = x.Price,
                 Service = x.Service.Name,
                 DateFrom = x.Date,
                 DateTo = x.Date_to,
                 WorkTimeTo = x.WorkTimeTo,
                 Id = x.Id,
                 EditingDate = x.CreatingDate

            })
            .ToList();
        return Json(proposals, JsonRequestBehavior.AllowGet);
    }

但是在这一行中Project = x.Region.Cities.,它看不到项目

这是图表 iа 它会更容易

我的麻烦在哪里?

更新 我这样重写方法

 var proposals = db.Proposals.Where(x=> x.Project.City.Region.UserToRegions)

            .Select(x=> new {
                 Project = x.Region.Cities.,
                 WorkTime = x.WorkTime,
                 Quantity = x.Quantity,
                 Price = x.Price,
                 Service = x.Service.Name,
                 DateFrom = x.Date,
                 DateTo = x.Date_to,
                 WorkTimeTo = x.WorkTimeTo,
                 Id = x.Id,
                 EditingDate = x.CreatingDate

            })
            .ToList();
        return Json(proposals, JsonRequestBehavior.AllowGet);
    }

现在,我没看到 UserToRegions.UserId。

Cities on the region 是一个集合,因此您需要在 Cities 上添加 .FirstOrDefault() 才能访问一个城市的项目集合。但这只会让您获得该地区第一个城市的项目,这可能不是您想要的。

如果您尝试 return 一个区域中的所有项目,您最好使用显式连接并稍微改变您的方法。

这里是您的起点:

http://www.dotnettricks.com/learn/linq/sql-joins-with-csharp-linq

你的 lambda 表达式通过连接操作组合了多个 table 但你只传递了没有参数的 where() 条件来连接所有其他 table 说 userid 而是连接多个 table像这样的一些参数

   var UserInRole = db.UserProfiles.
    Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
    (u, uir) => new { u, uir }).
    Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
    .Where(m => m.r.u.UserId == 1)
    .Select (m => new AddUserToRole
    {
        UserName = m.r.u.UserName,
        RoleName = m.ro.RoleName
    });

你可以参考这个来解决你的问题 here