0

I am having an issue where my project works on the current database, but when I use the code in my application to create a new database vis acode first, classes that were accessing views, are now being creating tables. Classes below have been shortened by removing other properties to show just relevant code.

I have a my DBContextClass:

public class MyDbContext : DbContext
{
     public MyDbContext ()
     {

     }
     public virtual DbSet<Order> Order{ get; set; }
     public virtual DbSet<v_OrdersByUser> v_OrdersByUsers { get; set; }
}

Here is my Order class:

[Table("Orders")]
public class Order
{
      [Key]
      public int Id { get; set; }
      etc
}

which creates a table as expected. But here is my SQL view class:

public class v_OrdersByUser
{
    [Key]
    public string UserName { get; set; }
    public int OrdersCount { get; set; }
}

but this class also creates a table.

How do I stop this from happening, yet maintain the ability to access the views, once I create them in the database?

Pedro Benevides
  • 1,970
  • 18
  • 19
Alan Schapira
  • 1,053
  • 4
  • 17
  • 32
  • Please, see this link: http://stackoverflow.com/questions/30239314/is-there-an-attribute-like-table-to-create-a-class-that-maps-to-a-view-in-ef Perhaps you need delete one of you clases. 'Order' or 'v_OrdersByUser'. – Jose Luis Jan 12 '16 at 09:26

3 Answers3

0

Try remove this line in you DbContext

public virtual DbSet<v_OrdersByUser> v_OrdersByUsers { get; set; }

If you add it as a DbSet, by default it will create a new table for you.

If you are using it as a view model, don't add it in this layer.

Hao
  • 266
  • 1
  • 12
  • But I need this line for when I call the view in my code. e.g. `Dictionary ordersByUser = _dbContext.v_OrdersByUsers .ToDictionary(a => a.UserName, a => a.OrderCount);` – Alan Schapira Jan 12 '16 at 09:19
0

To remove the table you need to remove the DbSet of v_OrdersByUser.

To work around this think of adding a user (or username) to the Orders table. Then you can simply sort all Orders based on usernames and using linq to retrieve the number of orders for each username from your Order DbSet.

0

You can do this with Data Annotations, like this:

[NotMapped]
public class v_OrdersByUser
{
    [Key]
    public string UserName { get; set; }
    public int OrdersCount { get; set; }
}

Or with Fluent Api, like this:

modelBuilder.Ignore<v_OrdersByUser>();
Pedro Benevides
  • 1,970
  • 18
  • 19