5

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 .

Community
  • 1
  • 1
Pickle
  • 215
  • 2
  • 6
  • 13

1 Answers1

7

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.

Márk Gergely Dolinka
  • 1,430
  • 2
  • 11
  • 22
  • When I added a key and run my code I get this msg "Migrations is enabled for context 'CatalogContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console." But I do have a view in my database with the same name. I don't understand why EF cannot pick up the views from DB. – Pickle Jun 13 '14 at 15:35
  • In one of your code there is _db.FooViews and in the db context there is a DbSet FooView. While you say that the View is called dbo.FooView Could you double check whether the context's property is named FooView and the view is dbo.FooView Because this another error indicates that the EF could not match the DbSet... to your view. – Márk Gergely Dolinka Jun 13 '14 at 15:57