C# 无法创建x类型的常量值,在此上下文中仅支持基元类型或枚举类型
我正在尝试将SQL语句转换为LINQ 我有这些模型:C# 无法创建x类型的常量值,在此上下文中仅支持基元类型或枚举类型,c#,entity-framework,linq,C#,Entity Framework,Linq,我正在尝试将SQL语句转换为LINQ 我有这些模型: public class GamesNight { public int id { get; set; } [DisplayName("Games Night Official Name")] public string EventName { get; set; } [DisplayName("Description")] public string EventDescription { get;
public class GamesNight
{
public int id { get; set; }
[DisplayName("Games Night Official Name")]
public string EventName { get; set; }
[DisplayName("Description")]
public string EventDescription { get; set; }
[DisplayName("Date and Time")]
[DataType(DataType.Date)]
public DateTime DateTime { get; set; }
public virtual ApplicationUser User { get; set; }
public bool Active { get; set; }
}
而GamesNightAttention,则或多或少地将用户链接到游戏之夜活动
public class GamesNightAttendance
{
[Key]
public int id { get; set; }
public virtual GamesNight GameNight { get; set; }
public virtual ApplicationUser UserName { get; set; }
public bool Attendance { get; set; }
}
因此,一个用户主持GamesNight,然后其他用户将能够通过gamesnightattendancemodel参加游戏之夜
我的问题是:
var userID = User.Identity.GetUserId();
var user = db.Users.First(x => x.Id == userID);
var result = from GNS in db.GamesNights
join GNA in db.GamesNightAttendance on GNS.id equals GNA.id
where GNS.Active & GNA.UserName == user
select new UpcomingGNAttendanceViewModel { GamesNight = GNS, Attendance = GNA.Attendance};
我得到一个例外:
Message=“无法创建“GNR.Models.ApplicationUser”类型的常量值。在此上下文中仅支持基元类型或枚举类型。”
您的命名约定对您没有帮助:
public virtual ApplicationUser UserName { get; set; }
那不是用户名,那是用户。该表还缺少实际保存关系的属性,以及保存GameNight
Id的属性。attention
属性也没有多大意义,因为您没有理由使用attention=false
创建gamesnightattention
该类应该更像这样:
public class GamesNightAttendance
{
public int Id { get; set; }
// add missing foreign key
public int GameNightId { get; set; }
// add missing foreign key
public int UserId { get; set; }
public virtual GamesNight GameNight { get; set; }
// fix name
public virtual ApplicationUser User { get; set; }
}
使用该模型,您现在可以执行以下操作:
var userId = User.Identity.GetUserId();
var result =
from gameNight in db.GamesNights
join attendance in db.GamesNightAttendance on gameNight.Id equals attendance.Id
where gameNight.Active && attendance.UserId == userId
select new UpcomingGNAttendanceViewModel
{
GamesNight = gameNight,
Attendance = attendance
};
你能展示SQL吗?也许我的建议会有所帮助。还有,你从哪里得到例外?这似乎不是linq问题。。。我认为这里的异常消息说明了一切,我怀疑这与我们在您的
UpcomingGNAttendanceViewModel
中看不到的代码有关。并且是GNA.UserName
的类型与用户的类型相同?GNS.Active&GNA.UserName
您的意思是&
?我注意到,“UserName”的类型是“ApplicationUser”和“user”我猜是“user”类型。如果是这种情况,您如何比较两个不同的对象?