Entity framework with column that may or may not exist - sql

I'm using entity framework that needs to be run against slightly different schemas of a database.
In one database a column does not exist,but in another it is a required (not null) field.
If I was writing SQL, I could query sys.columns to see if the columns exist and adjust my sql accordingly.
How would I do the same with Entity Framework?

You can check if the column exists then, if does not exists mark it as ignored via fluent API mapping
modelBuilder.Entity<MyEntity>()
.Ignore(_ => _.MyOptProperty);

Related

PostgreSQL - I get SQL Error [42P01] or [42703] if I don't add double quotes around table names or Fields

I'm using DBeaver to write script for my PostgreSQL database.
I have a PostgreSQL DB with Tables autogenerated by C#/EFCore (Microsoft ORM) - I receive SQL Error [42P01] if I don't add double quotes around table names when I cut and paste my ORM queries to DBeaver. I got [42703] for fields without double quotes. I do not have to add double quotes in C# code but it appears to be required in DBeaver?
example:
select * from Dnp3PropertyBase => SQL Error [42P01]
select * from "Dnp3PropertyBase" => OK, all results shown...
Does anybody know if I can change a parameter in DBeaver somewhere in order to enter table names and fields without double quotes?
Note: Using DBeaver 22.3.2 (latest on 2023-01-11)
Update After reading: Postgresql tables exists, but getting "relation does not exist" when querying
show search_path => public, public, "$user"
SELECT * FROM information_schema.tables => All tables are in public schema
SELECT * FROM information_schema.columns => All columns are in public schema
Question: How to be able to cut and paste my EFCore generated queries from Visual Studio output window to DBeaver query without having any errors regarding table names and field names?
First let me copy #a_horse_with_no_name comment:
Unquoted names are folded to lower case in Postgres (and to uppercase
in Oracle, DB2, Firebird, and many others). So SomeTable is in fact
stored as sometable (or SOMETABLE). However quoted identifiers have to
preserve the case and are case sensitive then. So "SomeTable" is
stored as SomeTable
Many peoples recommended me to go with snake case which I didn't want to go with initialy because all tables were auto generated by EF Core (Microsoft C# ORM). I told myself that Microsoft would do standard things. Microsoft use the exact "class" name in code as the table name , by default. That appears to me very logical in order to stay coherent and apply the same rules everywhere. C# recommended to use Camel case for classes so each table names end by default in Camel case instead of snake case.
PostgreSQL seems to promote users to use snake casing because they lower case every non double quoted names. According to a_horse_with_no_name, and I think the same, only PostgreSQL has the behavior of lower casing down every table names and field names which are not double quoted in SQL script. That behavior (changing casing for non double quoted names) appears to me as being very limitative. It also has hidden effect that could be hard to find for non initiated peoples coming from other DB world.
According to PostgreSQL doc, they recommend to use nuget package (.UseSnakeCaseNamingConvention()). It probably works fine for TPH (table per hierarchy) which is recommended by Microsoft for performance. But it does not works for table name for TPC (table per class) because of actual bugs in EFCore 7 (see Github project).
I received that message at the end of "update-database":
Both 'WindTurbine' and 'ResourceGenerator' are mapped to the table
'resource_generator'. All the entity types in a non-TPH hierarchy (one
that doesn't have a discriminator) must be mapped to different tables.
See https://go.microsoft.com/fwlink/?linkid=2130430 for more
information.
PostgreSQL doc : TPH supported OK but not for table in TPC (2023-01-12). I use TPC then I had to force each table name directly through TableAttribute.
My solution For table name, I use snake casing by manually add a "Table" attribute to each of my classes with the proper name like this sample:
[Table("water_turbine")]
public class WaterTurbine : ResourceGenerator
For fields, I use the EFCore.NamingConventions NugetPackage which works fine for fields names. Don't forget that if you have 2 classes mapped to the same object, it is because you are using TPC and did not force table name through TableAttribute.
This way all my table and fields names are snake casing and I can cut and paste any query dumped in my debugger directly in any SQL script window of DBeaver (or any SQL tool).

Entity Framework Core 3.1 not working with already defined snake case database(sql server) schema

I have an exiting database and I wanted to perform crud operations on it. I am using asp.net core 3.1
web api. All my database tables are defined in snake case naming convention e.g my_table_name
during fetching the records I get the exception
Error: {Microsoft.Data.SqlClient.SqlErrorCollection}
Message: Invalid column name 'my_table_nameID'.
This occurs only when I use Include statement in my query e.g
var temp = _sampleParentTableService.Queryable().Include(x => x.SampleChildTable).FirstOrDefault();
I tried to create 2 table Parent Table and child table with camel case naming convention e.g "MyTableName" and then used include statement and it works fine but when I tried to use same query with other table with snake case naming convention it throws an error.
Note: Relationship exists with the my_parent_table with my_child_table and column already exists in db with foreign key relationship e.g (pk ID ---> fk UserID) but Microsoft.EntityFrameworkCore Include statement does not find the column and create one "my_parent_table_nameID" which does not exists.
Tried to search on web and find some articles pointing to the extensions for code first migrations
I can not use migrations because most of my db relationships are mapped manually.
Also tried finding solution for "Invalid column name" and tried all workarounds e.g model annotations [ForiegnKey] etc.
found out that whenever we declare virtual ICollections<my_parent_table> link query tries to find pk fk relationship and if not found it tries to create one with default convention "OtherTableID"
also tried
modelBuilder.Entity().Ignore(t => t.OtherTableID);
resulting Invalid column name "OtherTableID1" exception
so I am assuming that problem is not with columns but with table names.
Expecting any solution or any middle ware that allow me to fetch records and allows me to perform crud operation on already defined database with snake case naming convention.

About Update Columns Null to Not Null in Code First

I have a database in which I have some tables in which certain columns are Null. I've made many API's in which I got that columns response are null this is hectic for mobile developers.
I want to alter those database columns to Not Null from SQL Management Studio. I am using my project code first method. Is any problem to direct update from database?
Yes, you have to make changes in Fluent Api of Entity Framework's Code First. Open your DatabaseContext file in which you will find "OnModelCreating" Method or search with "OnModelCreating" Method in your solutions.
Now find out the column of your table in "OnModelCreating" Method and update "WithOptional" to "WithRequired" as you update column from Null to Not Null.

VB.NET Changing Database Column Header Names Using Datagridview

I change the header name of a datagridview using the following code
Me.DataGridView1.Columns(0).HeaderText = "xxxx"
How can I apply this change to the Access database? Like when I rename first column in datagrid view I want the first column in database to be the same.
There isn’t a .Net API that allows changes to the gridview’s headers to propagate back to the database's columns. The gridview object supports binding to multiple sources (among those MS Access, Sql Server, Oracle, Object collections etc.) and does not contain the DDL logic required to update the SQL based data sources. Therefore, you will need to perform two separate actions: one on the access database and one within the asp.net code.

Formula after switching to NHibernate 3.2

I use this formula in NHibernate 3.1 :
.Formula("(SELECT b.Name FROM AdaptiveObjectModel.EntityType AS b WHERE (Structure = b.EntityTypeId))")
but after switching to NHibernate 3.2 receive this problem:
ambiguous column name Structure
The error comes from SQLserver, there are at least 2 tables with the column Structure. SQLserver does not know which one to chose. I guess that something changed in the way NHibernate interprets your query, and now sends all sql at once. Have a look in the logging or your profiler to see what the sql is your are sending to SQLserver. Then you can add the right alias before Structure.