3

I am using Entity Framework 7 RC1 Code First.

I have the following code

var resultset = await _db.Employees.FromSql<Employee>("dbo.sp_GetEmployees @DeptId="+ deptId).ToListAsync();

this works and fetches the data correctly.

however I need to change the stored proc to contain other properties than employees are returning.

So I adjust the stored proc and create a custom class EmployeeQuery that inherits from Employee with the additional properties.

However FromSql is a method on the DbSet of my DBContext

 public DbSet<Employee> Employees{ get; set; }

so I can do the same for EmployeeQuery by creating

 public DbSet<EmployeeQuery> EmployeeQueryItems{ get; set; }

and var resultset = await _db.EmployeeQueryItems.FromSql("dbo.sp_GetEmployees @DeptId="+ deptId).ToListAsync();

however creating a DBSet property this tells Entity Framework to create the table in the database and it's simply just a query object. So I don't want to do the above.

However apparently you can use the DbContext Set Method as mentioned in github and in this answer

so I change my code to var resultset= await _db.Set().FromSql("dbo.sp_GetEmployees @DeptId="+ deptId).ToListAsync();

However this gives me a runtime error

ex = {"Value cannot be null.\r\nParameter name: entityType"}

How do I get around this?

From this gitbub issue it doesn't seem possible without creating a dummy table.

Is there not a way to tell EF to not create the table? Like a NotMapped attribute on the DbSet?

Community
  • 1
  • 1
dfmetro
  • 4,462
  • 8
  • 39
  • 65

1 Answers1

3

I ran across this issue myself, and the only way I was able to resolve the problem was mapping a key for the POCO.

In a partial class along side the generated context, I override OnModelCreating and add:

modelBuilder.Entity<ClassName>(entity => entity.HasKey(e => e.Id));

Seems to satisfy EntityFramework.

Bill
  • 1,431
  • 10
  • 13
  • Can you expand on this please? So In an MVC controller I may have a method returning something like this: public JsonResult EmployeeUserRead() { `var result = (from user in appContext.Users join emp in context.Employees on user.Id equals emp.UserId select new { user, emp }).ToList(); return Json(result); }` I do not see where a modelBuilder comes into play?? – Paul Gorbas Mar 24 '17 at 21:13