We have a column that may or may not exist on a table. If it does not exist we wish to invoke the Fluent API ignore command:
modelBuilder.Entity().Ignore(c => c.FullName);
The issue is determining, within the confines of OnModelCreating, if the column exists before deciding to ignore.
I have looked at this solution: Entity Framework check if column exists during OnModelCreating
It leverages the Database.Connectionstring property, but thta is not available on Core, and if you use Database.GetConnection().ConnectionString then it fails due to trying to use the DbContext during model creation.
How can I access the connection string that I need from here? Is there a different way to check if the column exists?
CodePudding user response:
There's not a good way to do this using the DbContext instance.
Instead access the connection string from configuration and query the database directly with a DbConnection to determine if the column is present. You can do this at startup, or at startup inject a separate service that can access the database metadata and drive the conditional fluent configuration inside OnModelCreating.
CodePudding user response:
ConfigurationManager.ConnectionStrings
should expose it.
If the column might be there or might not, you need to ensure that it is never used in Query expressions like Where
or even Select
/ ProjectTo
clauses. These would only work if the column exists and is mapped, so you pretty much need to treat it as ignored or have conditional logic scattered around if you do want to use it such as in a Select
projection.
It might be more reliable to remove it and leave it a computed value in your view models with a configurable option for the desired format, (such as LastName, FirstName vs. FirstName LastName if this applies to a person's name) then handling Insert/Update as a separate conditional action with a bounded DbContext instance which is configured to use it on the class. This could even be handled on the DbContext SaveChanges
override, so that updates or inserts could be intercepted, discarded from the initial DbContext, and done by the bounded DbContext if that client is using that column. (Necessary in the case where handling Inserts where FullName is a non-null-able column)