0

Any idea why this doesn't work

return View((from u in db.Users
            select new Models.Users()
            {
                Id = u.Id,
                Username = u.Username,
                Password = "-"
            }).ToList());

And this works like a charm? :]

return View(db.Users.SqlQuery("SELECT Id, Username, '-' AS Password FROM Users"));
poison64
  • 89
  • 9

1 Answers1

0

Since you didn't really give a ton of information I'm gonna take a shot in the dark. EF doesn't allow you to select to a class that represents a database entity. I'm assuming the Models.Users class is the same class being used in your db.Users? You should just be able to create like a UserDto with the same fields and I think that will work. If it doesn't give more info and I'll try to help more.

GBreen12
  • 1,640
  • 15
  • 33
  • Ok, maybe my question should be a little different :) In my view I have set the @model to Models.Users so I get why the linq example doesn't work. I just don't understand why the SqlQuery does. Shouldn't it be blocked the same way linq is blocked? – poison64 Aug 16 '17 at 05:59
  • "Shouldn't it be blocked the same way linq is blocked?", in other words: Shouldn't EF require creating a DTO for the SqlQuery as well? – poison64 Aug 16 '17 at 06:47
  • I believe it's because in the sql query you aren't actually creating the entity yourself. You are selecting specific fields but EF is creating the actual object which is what EF always does. For example, if you tried to add `.Select(u => new Models.Users(){ Id = u.Id, Username = u.Username, Password = "-" });` that would fail because you can't select into a mapped entity. – GBreen12 Aug 16 '17 at 15:43
  • In other words, the two examples are doing two different things. – GBreen12 Aug 16 '17 at 15:43