Scaffold-DbContext throw ArgumentNullException - sql-server

I get the following exception when I try to scaffold one of our databases.
For foreign key FK_ActivityEvent_ActivityCode on table dbo.ActivityEvent, unable to find the column called UniqActivityCode on the foreign key's principal table, dbo.ActivityCode. Skipping foreign key.
For foreign key FK_Line_Line on table dbo.Line, unable to find the column called UniqLine on the foreign key's principal table, dbo.Line. Skipping foreign key.
For foreign key FK_MarketingLine_MarketingLine on table dbo.MarketingLine, unable to find the column called UniqMarketingLine on the foreign key's principal table, dbo.MarketingLine. Skipping foreign key.
System.ArgumentNullException: Value cannot be null.
Parameter name: column
at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.GetPropertyName(DatabaseColumn column)
at System.Linq.Enumerable.SelectListIterator`2.ToArray()
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitPrimaryKey(EntityTypeBuilder builder, DatabaseTable table)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitTable(ModelBuilder modelBuilder, DatabaseTable table)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitTables(ModelBuilder modelBuilder, ICollection`1 tables)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitDatabaseModel(ModelBuilder modelBuilder, DatabaseModel databaseModel)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.Create(DatabaseModel databaseModel, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, IEnumerable`1 tables, IEnumerable`1 schemas, String namespace, String language, String contextDir, String contextName, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions)
at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Value cannot be null.
Parameter name: column
I successfully scaffolded one of our databases so I'm sure I'm using the scaffold command properly. Also, I can access the database using the connection string I entered on the Scaffold-DbContext command.
I installed the following packages:
install-package microsoft.entityframeworkcore.sqlserver
install-package microsoft.entityframeworkcore.tools
Using .NET Core Console App 2.1 on Windows 10.
Not sure if this is related but I get the following message when I try to expand the Database Diagrams in ssms. (I don't get this message on the other database that I successfully scaffolded)

Related

How do I create a method binding a stored procedure in Entity Framework 6?

How do I create a function mapping a SQL stored procedure?
I have tried
var order = context.CustomerDetails.SqlQuery("DisplayTotalOrders #CustomerID", new SqlParameter("CustomerID", "1"));
var order = context.CustomerDetails.SqlQuery("DisplayTotalOrders #CustomerID", 1);
but nothing has worked.
Error message is shown as below. And this method seems quite an ad-hoc execution. Is there a way destined to create a method which binds a SQL Server stored procedure in EF? I am not talking about just INSERT, UPDATE, DELETE functions. I am referring to executing any SQL Server stored procedure.
Unhandled Exception:
System.Data.Entity.Core.EntityCommandExecutionException: The data
reader is incompatible with the specified
'TestEF_Code.CustomerDetail'. A member of the type, 'CustomerID', does
not have a corresponding column in the data reader with the same name.
at
System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.GetMemberOrdinalFromReader(DbDataReader
storeDataReader, EdmMember member, EdmType currentType, Dictionary2 renameList) at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.GetColumnMapsForType(DbDataReader storeDataReader, EdmType edmType, Dictionary2 renameList) at
System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.CreateColumnMapFromReaderAndType(DbDataReader
storeDataReader, EdmType edmType, EntitySet entitySet, Dictionary2 renameList) at System.Data.Entity.Core.Objects.ObjectContext.InternalTranslate[TElement](DbDataReader reader, String entitySetName, MergeOption mergeOption, Boolean streaming, EntitySet& entitySet, TypeUsage& edmType) at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass691.b__68()
at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass691.b__67()
at
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) at System.Data.Entity.Internal.Linq.InternalSet1.<>c__DisplayClass11.b__10()
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext() at System.Linq.Enumerable.Single[TSource](IEnumerable1 source) at
TestEF_Code.Program.Main(String[] args) in
B:\Users\trio\Programming\TestEF-Code\TestEF-Code\Program.cs:line 17

Npgsql error - The store type 'nvarchar(MAX)' could not be found in the Npgsql provider manifest

I'm new to Postgres and using npgsql as the provider to EF6. Just to provide some context, I've recently migrated our SQL Server to Aurora Postgres using the AWS DMS. That seems to be all good; I can see data and tables, etc...Now, I'm trying to hook up our application (in C# using EF6) to switch over to the Postgres DB. I've gone through all the steps to setup npgsql and npgsql EF provider, and making a new additional db context to connect to the Postgres DB. All seems good at this point.
I decided to do a simple EF query to fetch.
var courses = context.Courses.FirstOrDefault();
I got this exception:
An Internal Server Error has occurred|System.InvalidOperationException: The store type 'nvarchar(MAX)' could not be found in the Npgsql provider manifest
at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.<>c__DisplayClass47_0.<Configure>b__0(Tuple`2 pm)
at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, ICollection`1 entitySets, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Data.Entity.QueryableExtensions.CountAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at System.Data.Entity.QueryableExtensions.CountAsync[TSource](IQueryable`1 source)
Anyone know what this means?
Take a look at these EF docs on how to manage migrations with multiple databases.

MS-SQL server throws error when two foreign keys are set on same table using GORM

I am doing database migrations using GORM. So I define structs and run them through GORM's AutoMigrate function.
type Person struct {
ID string `gorm:"type:varchar(36);primary_key"`
}
err := db.Table("persons").AutoMigrate(&Person{}).Error
type Address struct {
ID string `gorm:"type:varchar(36);primary_key"`
PersonID string `gorm:"column:person_id;type:varchar(36);NOT NULL"`
}
err = db.AutoMigrate(&Address{}).Error
err = db.Model(&Address{}).AddForeignKey("person_id", "persons(id)", "NO ACTION", "CASCADE").Error
type Contact struct {
ID string `gorm:"type:varchar(36);primary_key"`
AddressID null.String `gorm:"column:address_id;type:varchar(36);NOT NULL"`
PersonID string `gorm:"column:person_id;type:varchar(36);NOT NULL"`
}
err = db.AutoMigrate(&Contact{}).Error
err = db.Model(&Contact{}).AddForeignKey("address_id", "addresses(id)", "NO ACTION", "CASCADE").Error
err = db.Model(&Contact{}).AddForeignKey("person_id", "persons(id)", "NO ACTION", "CASCADE").Error
In the above code, which ever is the second call to the AddForeignKey function on Contacts table is giving error :
mssql: Could not create constraint or index. See previous errors.
Even if I move person_id foreign key above address_id foreign key, then address_id foreign key fails.
I am running MS-SQL server using latest docker container setup(microsoft/mssql-server-linux:latest). Is this something regarding naming of constraint. If yes, then how can we set using GORM? Everything works fine with My-SQL.
It would be really helpful if I get a solution. I cannot run raw queries. Migrations have to be done using GORM only.
Thank You
Multiple foreignkeys can't have 'no action', 'cascade' on the same table. If u use no action, no action u can but u have to handle deletion and updating your self. What I usually do is turn on logmode and copy paste the log sql statement into SQL. This will give u a more clear error.

How to map two tables and not make any changes when mapping legacy database tables in Grails?

I'm new to Grails and mapping and I have something that looks like this.
I have two domain classes and I need to make a relationship between them, and when the relationship is done that no changes would be made to existing tables from my PostgreSQL database.
class Insurance{
Integer id
String osg_name
String osg_logo
String osg_email
String osg_link
static hasMany = [ insurancePackage: InsurancePackage]
static constraints = {
id(blank: false)
osg_name (blank: false, size: 0..155)
osg_logo (size: 0..155)
osg_email (blank: false, size: 0..100)
osg_link (size: 0..155)
}
static mapping = {
table name: "insurance", schema: "common"
version false
id generator :'identity', column :'osg_id', type:'integer'
}
}
class InsurancePackage{
Integer id
Integer osg_id
String osgp_comment
Integer tpo_id
String osgp_link
String osgp_label
//static belongsTo = Insurance
static belongsTo = [insurance: Insurance]
static constraints = {
id(blank: false)
osg_id (blank: false)
osgp_comment (blank: false, size: 0..500)
tpo_id (blank: false,)
osgp_link (blank: false, size: 0..155)
osgp_label (blank: false, size: 0..10)
}
static mapping = {
table name: "insurance_package", schema: 'common'
version false
id generator :'identity', column :'osgp_id', type:'integer'
}
}
This is the error that I'm getting
Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - Unsuccessful: alter table revoco.insurance_package add column insurance_id int4 not null
| Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - ERROR: column "insurance_id " contains null values
| Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - Unsuccessful: alter table revoco.insurance_package add constraint FK684953517A89512C foreign key (insurance_id ) references revoco.insurance
| Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - ERROR: column "insurance_id " referenced in foreign key constraint does not exist
So I cant connect the two tables and I'm getting the same error, for some reason Grails are trying to find insurance_id but that is not defined in classes and they are trying to alter my tables and I don't want that to happen.
You are created a new column in the insurance_package table that holds a foreign key to the insurance table. (hasMany and belongsTo --> one-to-many)
The problem here is that the column has a NOT NULL contraint by default but the table appears to have already data in it.
The question is now: What to do with the data already contained in the table. Grails wants to set the NOT NULL constraint but can't because there are already in there and because you have just created the column and the values are NULL
You have 3 options depending on your use case:
delete the values already contained in the table (maybe not wanted)
Go in your db management tool and set a foreign key for those rows and then restart the server. The error should disappear
set the constraint for your insurance reference (belongsTo) in your "InsurancePackage" object to be nullable:true

HibernateException: Missing table error for a Join Table using Grails 2.0.2 on MS SQL legacy database

I am trying to get a many-to-many relationship working using Grails 2.0.1 on Windows 7. I have exhausted both Google, this site, and my Grails books. Nothing worked. I am connecting to a MS SQL Server 2005 database that I have READ only privileges on and yes - it is a legacy database. Everything in the 2 individual tables works fine (views OK & all) but when I try to add the join table code I get an error:
org.hibernate.HibernateException: Missing table: dbo.IN_USR_DRAWING_PRIV
The table does indeed exist and I can see it fine using IntelliJ's IDEA 10.5 Data Sources view & the MS SQL Server Management Studio. The relevant part of the error is this (I can send more ... much more if needed) :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is org.hibernate.HibernateException: Missing table: dbo.IN_USR_DRAWING_PRIV
Here are the 2 domain classes :
class Drawing {
static hasMany = [appusers:Appuser]
String id
String drawingId //this is in the join table
String drawingName
static transients = ['name']
void setName(String name) {
id = name
}
String getName() {
return id
}
static mapping = {
table name: "IN_DRAWING", schema: "dbo"
version false
id column: 'DRAWING_ID', generator:'identity', insertable:false, updateable:false
drawingId column: "`DRAWING_ID`",insertable:false, updateable:false //this is in the join table
drawingName column: "`DRAWING_NAME`"
appusers column: '`USR_ID`',
joinTable: 'IN_USR_DRAWING_PRIV'
}
}
class Appuser {
static belongsTo = Drawing
static hasMany = [drawings:Drawing]
String id
String usrId //this is in the join table
String usrName
static transients = ['name']
void setName(String name) {
id = name
}
String getName() {
return id
}
static mapping = {
table name: 'IN_USR', schema: "dbo"
version false
id column:'USR_ID', generator:'identity', insertable:false, updateable:false //this is in the join table
drawings column: 'DRAWING_ID',
joinTable: 'IN_USR_DRAWING_PRIV'
usrName column: "`USR_NAME`"
}
}
And here is the schema for the join table:
dbo.IN_USR_DRAWER_PRIV
USR_ID (PK, varchar(23), not null)
DRAWING_ID (PK, FK, varchar(23), not null)
PRIV_ID (PK, int, not null)
GRAG reports it has a composite key of all 3 columns, which it does along with a FK on DRAWING_ID.
Solutions that I have tried :
This code (which fails with the "Missing Table" exception.
Adding a domain controller for the join table - same result.
Any hints/clues/solutions appreciated.
I fixed this by using Groovy SQL directly and passing in the T-SQL.

Resources