Specifying Schema Names in Entity Framework Core Code-First Models
This seemed like such a simple thing, and it turned out to be, but I couldn’t for the life of me find a simple explanation by searching. I am building my first ASP.Net Core Razor app using .Net Core 2.2 and EF Core, and my database uses schema names other than “dbo”.
The default syntax for specifying a non-default table in a model class is
[Table(“tblSomethhingElse”)]
public class Something
{ etc. }
which works fine for specifying the table name when it is different from the desired entity name. In my case, I am using views to define a logical data model for something that is independent of the physical model (which is kind of messy, and needs a few validation checks built into the query), and I like to prepend view names with “vw”, so the “tables” (views, really) have names that are different than the entity set names.
So far, so good, but I defined the views in a specific schema other than “dbo” that I use for code that is primarily for use by the web app, so that I can set specific permissions on it. So I tried “
[Table(“sch.tblSomethhingElse”)]” where “sch” is the schema name. Bad guess. Doesn’t work.
I noticed however, that the Table attribute has a property called “Schema”. After some searching and coming up with nothing reasonable, I read through the Microsoft docs for Table. Nothing was mentioned about property syntax, but there was a syntax for named parameters. That did the trick. What I ended up with was
[Table(“tblSomethhingElse”, Schema=”sch”)]
public class Something
{ etc. }
Now I am on to the next problem, or should I say “learning experience”. I may have answered this question years ago when I last used EF, but I didn’t blog about it (at least I hope I didn’t and then forget about it), so there it is.
thankiu very much!!!
You also have ‘modelBuilder.HasDefaultSchema(“mySchema”);’ in your context class
Yes, the fluent API provides that method. I had not used Entity Framework for five years when I posted that. Back then I was trying, as much as possible, to use attributes rather than fluent because I find them easier to read, and because dividing the model definition across two files is somewhat inconvenient. Whatever works, though. Thank you.
Now I have no choice but to use fluent API, because many of my primary keys are going composite as I migrate to a multi-tenant database, where the 2nd column of the PK is the customer ID, and as I configure EF Core 5 many-to-many navigation against my existing join tables. To maintain readability for the PKs, I add comments to the PK properties in the model class.