0

I use MVC 5 razor and I'm new to this.

I want to only display the projects that the user created. In my table project there is a FK to User as User_id.

I've used the ApplicationUser model that is auto rendered at the start from a new project in MVC.

In my project controller:

private UserManager<ApplicationUser> manager;

public ProjectController()
{
    manager = new UserManager<ApplicationUser>(
        new UserStore<ApplicationUser>(db));
}

// GET: /Project/
[Authorize]
public ActionResult Index()
{
    var currentUser = manager.FindById(User.Identity.GetUserId());
    var proj = from p in db.Projects
               where p.User == currentUser
               select p;
    return View(db.Projects.ToList(proj));
}

The error.

Unable to create a constant value of type 'herexamen800.Models.ApplicationUser'. Only primitive types or enumeration types are supported in this context.

Yuliam Chandra
  • 13,858
  • 12
  • 49
  • 66
Keeper01
  • 243
  • 2
  • 4
  • 12

1 Answers1

2

Just compare the id not the reference.

var userId = User.Identity.GetUserId();
var proj = from p in db.Projects
           where p.User.Id == userId
           select p;
Yuliam Chandra
  • 13,858
  • 12
  • 49
  • 66
  • 1
    Thanks for solving the problem! – Keeper01 Aug 28 '14 at 08:19
  • You probably have a UserId column in your Project object, I would compare userId to p.UserID instead of p.User.Id, it should remove a JOIN in the generated query – Marien Monnier Aug 28 '14 at 08:30
  • @MarienSoft'It, the FK column name is `User_Id` that is usually a default FK name for independent association, unless the property name is explicitly set to `public PropertyType User_Id {get;set;}` or change the column name by using fluent api – Yuliam Chandra Aug 28 '14 at 08:31
  • @YuliamChandra indeed, I'm used to explicitly create a property with the ID. But, my point was to avoid a JOIN in the generated query by using either the generated FK column or the created FK column ;) – Marien Monnier Aug 28 '14 at 08:44
  • @MarienSoft'It, I agree with your point, [foreign key association is a lot of easier than independent association](http://stackoverflow.com/questions/5281974/code-first-independent-associations-vs-foreign-key-associations), but in this case the generated query will not produce join result `WHERE [Extent1].[User_Id] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=123` – Yuliam Chandra Aug 28 '14 at 08:48