gpt4 book ai didi

entity-framework-4 - 无法创建类型为 'T' 的常量值。在此上下文中仅支持原始类型 ('such as Int32, String, and Guid' )

转载 作者:行者123 更新时间:2023-12-04 05:56:39 26 4
gpt4 key购买 nike

我看到很多关于此错误的问题,但有人可以告诉我为什么我的代码中出现此错误?
我的应用程序中有用户和组,它们有很多关系:

public class Group
{
[Key]
public int GId { get; set; }

public string GName { get; set; }

public virtual ICollection<UserProfile> Members { get; set; }

public Group()
{
Members = new HashSet<UserProfile>();
}
}
public class UserProfile
{
[Key]
public Guid UserId { get; set; }

[Required]
public string UserName { get; set; }

public virtual ICollection<Group> Groups { get; set; }

public UserProfile()
{
Groups = new HashSet<Group>();

}
}

我想获得用户加入的所有组并将其传递给 ViewBag,因此:
UserProfile user = core.Profiles.Find(1);
//ok, no error in controller, but view...
ViewBag.JoinGroups = core.Groups.Where(g => g.Members.Contains(user));

但我在 View 中收到错误:
@if (ViewBag.JoinGroups != null)
{
foreach (var g in ViewBag.JoinGroups)//My issue start here
{
<p>@g.GId</p>
}
}

它说:

Unable to create a constant value of type 'Project.Model.UserProfile'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.



我错过了什么吗?

最佳答案

消息很明确:EF Linq 查询不支持传递实体。

您可以通过更改此部分来解决它:

UserProfile user = core.Profiles.Find(1);
ViewBag.JoinGroups = core.Groups.Where(g => g.Members.Contains(user));

为了这:
ViewBag.JoinGroups = core.Groups.Where(g => g.Members.Select(x => x.UserId)
.Contains(1));

关于entity-framework-4 - 无法创建类型为 'T' 的常量值。在此上下文中仅支持原始类型 ('such as Int32, String, and Guid' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9446867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com