Reputation: 215
I have created a SQL Server view which performs some reasonably complex logic on other tables/entities and exposes a series of columns.All I wanted to access this view in entity framework code first approach and when I saw discussion in this I just followed and created a class "FooView.cs" and added it to DbSet<FooView>
property in my DbContext class.
public class FooView
{
public string PartNumber { get; set; }
public string PartType { get; set; }
}
public class CatalogContext : DbContext
{
public DbSet<FooView> FooView { get; set; }
}
But when I run my code I get an error saying : EntityType 'FooView' has no key defined. Define the key for this EntityType.
CatalogContext _db = new CatalogContext();
var l = _db.FooViews.Select(_ => _.PartNumber);
But all I want it to do is access my view from DB dbo.FooView
Easier solution for this problem will be creating a EDMX file and accessing the view, But I do not want to have 2 DB contexts.
I would really appreciate if anyone can help me with it, thanks a lot .
Upvotes: 5
Views: 6822
Reputation: 1460
Your problem is exactly what the error message says: the Entity Framework cannot decide what the key is in the FooView. To solve this problem just add the [Key] attribute to your PartNumber (if that is a unique key):
public class FooView
{
[Key]
public string PartNumber { get; set; }
public string PartType { get; set; }
}
This should solve your problem.
Upvotes: 7