nvcnvn
nvcnvn

Reputation: 5175

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

I see alot of question about this error, but some one can tell me why I get this error in my code?
I have the User and Group in my app, they have many to many relationship:

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>();

    }
}

I want to get all the Group that a User has Join ans pass it to a ViewBag, so:

UserProfile user = core.Profiles.Find(1);
//ok, no error in controller, but view...
ViewBag.JoinGroups = core.Groups.Where(g => g.Members.Contains(user));

But I get the error at View:

@if (ViewBag.JoinGroups != null)
{
    foreach (var g in ViewBag.JoinGroups)//My issue start here
    {
        <p>@g.GId</p>
    }
}

And it said:

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.

Do I missing any thing?

Upvotes: 2

Views: 2203

Answers (2)

Diego Mijelshon
Diego Mijelshon

Reputation: 52735

The message is clear: EF Linq queries do not support passing entities.

You can work around it by changing this piece:

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

For this:

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

Upvotes: 2

Gert Arnold
Gert Arnold

Reputation: 109185

This is not specific to a ViewBag or anything. It's just the deferred execution pitfall: not until the foreach is the query executed. You would have seen the exception earlier by doing core.Groups.Where(g => g.Members.Contains(user)).ToList();.

By the way you pose it is clear that you already know that referencing non-scalar variables is not supported in entity framework, but allow me to mention it for the sake of completeness.

Upvotes: 1

Related Questions