Best practices - working with views, key or no key designation during v3 to v6 upgrade
Hello,
I am working with multiple .NET functions that use a mix of tables, views, and stored procedures that are defined via DbSets. After upgrading from EF Core 3 to EF 6, we got a lot of errors on the views and stored procedures because they were not designated without a key in the OnModelCreating method.
e.g. The entity type 'vName' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'.
There's no problem fixing the stored procedure-related DbSet, but going through the views, some of the previous devs would put [Key] above some of the View fields, a few were actually being defined as tables, e.g.
modelBuilder.Entity<vView1>(entity =>
{
entity.ToTable("vView1");
entity.HasMany(req => req.View2List)
.WithOne(p => p.vView1Object)
.HasForeignKey(p => p.View1Id);
});
Where the objects being referenced are instances of the DbSet model or a list of them.
We're not working code-first - we don't seem to be doing migrations, but have a separate project supported by DBAs who have SQL scripts. None of the original devs are working on this project anymore so I am missing possible context for the decisions they made when defining these views.
I am still wondering, is there any case where it makes sense to:
- State a view has a key (e.g. [Key] on a unique ID feeding into it)? What issues would this cause leaving it in? Is this an anti-pattern?
- Ditto with stating a view is a table - is there any benefit or reason we might want to leave this, or is this another anti-pattern/potential workaround for errors in prior versions I should theoretically be OK fixing into .ToView() etc. ?