Unable to update the EntitySet '' because it has a DefiningQuery - asp.net-mvc

I'm having this error in this code:
Unable to update the EntitySet 'Ingredient_Quantity' because it has a
DefiningQuery and no <InsertFunction> element exists in the
<ModificationFunctionMapping> element to support the current operation.
The code.
Ingredient ing = new Ingredient();
ing.name = ingredientVM.name;
ing.Ingredient_Type_id = ingredientVM.typeId;
ing.UOM_id = ingredientVM.uomId;
ing.is_deleted = 0;
db.Ingredients.Add(ing);
db.SaveChanges();
int latestIngredientId = ing.id;
Ingredient_Quantity iq = new Ingredient_Quantity
{
Ingredient_id = latestIngredientId,
quantity_as_of = DateTime.Now,
quantity = (double)ingredientVM.quantity
};
db.Ingredient_Quantity.Add(iq);
db.SaveChanges(); // HERE IS WHERE I'M GETTING THE ERROR
From what I am seeing in the internet, it's because that my Ingredient_Quantity is seeing every column as Entity Key. I don't know if this is right.
How can I change this? Any advice?

You have 2 issues there:
1) The most common reason from "Unable to update the EntitySet X because it has a
DefiningQuery" is that entity table missing a primary key constraint in database. You can add primary key to identity column either by SSMS table designer or using this query (note that primary key should be only set to one column):
ALTER TABLE Ingredient_Quantity ADD CONSTRAINT (Ingredient_id) PRIMARY KEY (Ingredient_id)
Note that a table without primary key treated as view during entity mapping (EF uses class to define table/view name & properties to refer each table/view columns), and a view can't be inserted/updated (only SELECT allowed).
2) Multiplicity conflicts with the referential constraint usually refers to conflict between source table column definition & target table foreign key. You can fix the multiplicity settings using these steps:
a) Define the relationship first. The relationship criteria should be like this:
One-to-many relationship if you have non-nullable foreign key (e.g. int)
Zero/one-to-many relationship if you have nullable foreign key (e.g. int?)
b) Open EDMX file in designer, right-click empty design area, select "Add New" => "Association".
c) Choose "Multiplicity" setting which best fit with your foreign key configuration (see the image below as example). You can select 1 (One) or 0..1 (Zero or One), depending on non-null/nullable foreign key on second table.
Related issues:
It has a DefiningQuery but no InsertFunction element... err
Problems with multiplicity and EF 6
Entity Framework Database Update First Multiplicity conflicts

Related

Can't insert rows into SQL Server table that contains triggers ( F Sharp SQL Provider )

I am using the Sqlprovider driver and hitting an issue on creating new records - that appears to make the driver useless.
let foundProductMaybe = query {
for p in ctx.Dbo.Products do
where (p.DefaultSupplierSku.Value = pl.supplierSku)
select (Some p)
exactlyOneOrDefault
}
match foundProductMaybe with
| Some foundProduct ->
updateProduct(foundProduct,pl,ctx)
| None -> addProduct(pl, ctx)
product.Id <- Guid.NewGuid()
product.Code <- "some code"
.... etc
ctx.SubmitUpdates()
I get the error:
System.Data.SqlClient.SqlException: 'The target table 'dbo.Products' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO
Is there a workaround for this?
This is an issue related to SQL Server, not necessarily SQLServerProvider, it seems to me. Here's an article that discusses the mechanism of this behaviour. https://techcommunity.microsoft.com/t5/sql-server/update-with-output-clause-8211-triggers-8211-and-sqlmoreresults/ba-p/383457
The code that generates the OUTPUT statemens in the SqlProvider appears to be here: https://github.com/fsprojects/SQLProvider/blob/8afaad203efe2b3b900a2ad1a6d8a35d66ebe40a/src/SQLProvider.Runtime/Providers.MsSqlServer.fs#L370
The OUTPUT clause is generated only if the table has primary key.
Perhaps you can change the table and replace the primary key with UNIQUE constraint, which is pretty close in the functionality to the PK constraint and should not affect you in your case.
https://learn.microsoft.com/en-us/sql/relational-databases/tables/create-unique-constraints?view=sql-server-ver15
The Unique constraints (and primary keys) are implemented as indexes on the table. Since you use a nonsequential GUID, you might consider ensuring that these indexes are created as NONCLUSTERED.

Fluent Migrate Candidate Key

I have two tables One named "Root" which has columns Id,RootNumber, in which Id is primary Key.
Now when I tried to create another table with RootNumber as the foreign key I get below error
InnerException {"There are no primary or candidate keys in the
referenced table 'dbo.Root' that match the referencing column list in
the foreign key ("FK_CNTR_Root", \r\nCould not create constraint or
index. See previous errors."} System.Exception
{System.Data.SqlClient.SqlException}
this.CreateTableWithId32("CNTR", "Id", s => s
.WithColumn("CNTRNumber").AsString(10).NotNullable()
.WithColumn("CNTRName").AsString(10).NotNullable()
.WithColumn("RootNum").AsInt32().NotNullable()
.ForeignKey("FK_CNTR_Root", "Root", "RootNumber")
The error is very clear. You can make only the PrimaryKey column to be referenced as ForeignKey in another table. So Either make Id as a foreign key in other table or Change RootNumber to PrimaryKey of Root table.
Refer to this basic Foreign Key definition.

Sequelize : how to join on foreign keys

I'm using Sequelize and Node.js, and I need to join 2 tables on 2 foreign keys,
tableA.hasOne(tableB, { foreignKey: 'fk_tableB' });
tableB.belongsTo(tableA, {foreignKey: 'fk_tableB' });
(by the way, I don't understand the functionality of "targetKey")
but I can only obtain a join on tableA.primaryKey = tableB.fk_tableB.
How can I replace the tableA.primaryKey by tableA.fk_tableA?
I also tried to define twice tableA : in 2 different structures (one with the real primary key and the other with fk_tableA as primary key), but it's also not working (because I need the real tableA mode in another place).
Has someone an idea? Is it a bug from Sequelize?
How can I replace the tableA.primaryKey by tableA.fk_tableA?
There is no tableA.fk_tableA. But if there were, we would expect you to have named it that because column tableA.fk_tableA is a FK to a key column in tableA. Because that's the convention for naming a column fk_tableA. Similarly we would expect a belongTo like yours that adds a column that is a FK to the tableA PK to call it fk_tableA, not fk_tableB. Just like your hasOne gives tableA a column fk_tableB to the tableB PK. (If you want a FK to be to some other column than the PK then you say so via targetKey.)
If you so named FKs after their target table, you seem to want tableA.fk_tableB = tableB.fk_tableA. The way you have named them now, you seem to want tableA.fk_tableB = tableB.fk_tableB.
I need to join 2 tables on 2 foreign keys
It is extremely unlikely that you need the join above. Declaring a column to be a FK says that a value of the source/referencing column is always a value of the target/referenced column. Here targets are PKs. Such a join on a FK to one table and a FK to another table will only return rows that share the same PK value, even though the PKs are from different tables.

TEntity Remove method fails on many to many relationship that was created using database first

I am using Entity Framework 6.1.3 and a database first approach.
It is a small database with a many to many relationship between Tags and BoxedItems, a table named ItemsTags holds the relationship.
I get an exception when using the scaffolded code to delete a BoxedItem:
db.BoxedItems.Remove(boxedItem);
db.SaveChanges();
SqlException: The DELETE statement conflicted with the REFERENCE
constraint "FK_ItemsTags_Items". The conflict occurred in database
"TimeBox", table "dbo.ItemsTags", column 'IdItem'.
The relationship table code is bellow. The PK for BoxedItem needs to be a Guid and for Tags is a INT IDENTITY (1, 1).
CREATE TABLE [dbo].[ItemsTags] (
[IdItem] UNIQUEIDENTIFIER NOT NULL,
[IdTag] INT NOT NULL,
CONSTRAINT [PK_ItemsTags] PRIMARY KEY CLUSTERED ([IdItem] ASC, [IdTag] ASC),
CONSTRAINT [FK_ItemsTags_Tags] FOREIGN KEY ([IdTag]) REFERENCES [dbo].[Tags] ([Id]),
CONSTRAINT [FK_ItemsTags_Items] FOREIGN KEY ([IdItem]) REFERENCES [dbo].[BoxedItems] ([Id])
);
Would the EF auto generated code work out of the box if my BoxedItem PK was INT IDENTITY (1, 1)? EF seems to like it more for auto generated code.
Is there a smarter way to delete the BoxedItem, other than a custom SQL instruction?

Inserting data as foreign key constraint in grails

Continuing to the post of reading-from-XML-and-storing-the-values-in-database-using-grails
am facing an another problem in it. As the employee id is related to other tables as foreign key how am suppose to insert the data into the database without conflict what i want to add in grails code to avoid the below displayed error.
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:Cannot
add or update a child rowL a foreign key constraint fails.. ( CONSTRAINT 'EMPLOYEE_ID_HEADER'
FOREIGN KEY ('EMPLOYEE_ID') REFERENCES 'employee_header'('employee_id'))
here employee_id is a column and employee_header is a separate table that contains employee_id as a foreign key.
Finally I got the answer, when you are inserting the values in database the related foreign key tables will get affects initially. So to handle this situation we have to insert the foreign key related table at first then the table we need to add exactly.
For the reference, at first I had given the code like this
sql.executeInsert("insert into order_item (order_id,product_id,
order_item_seq_id) values (${order_id},${product_id},${order_item_seq_id})")
sql.executeInsert("insert into product(product_id) values(${product_id})")
This first inserts the order_item table then the foreignkey constraint table product, so the data did not inserted. So the correct code is
sql.executeInsert("insert into order_header(order_id) values(${order_id})")
sql.executeInsert("insert into product(product_id) values(${product_id})")
sql.executeInsert("insert into order_item (order_id,product_id,
order_item_seq_id) values (${order_id},${product_id},${order_item_seq_id})")
Now this inserts the data successfully without errors.

Resources