I am using TypeOrm with Postgres. I am having the below entity (minified)
class A {
#OneToMany()
b:B
#OneToMany()
c:C
}
class B {
#ManyToOne()
a: A
}
class C {
#OneToMany()
d: D
#OneToMany()
e: E
#ManyToOne()
a: A
}
class D {
#ManyToOne()
c: C
}
class E {
#ManyToOne()
c: C
}
When I am trying to update entity A with a new items added to the collection c, d it is working fine and foreign keys are getting updated correctly. But when I am trying to update the same entity again after updating fields c,d, I can see that foreign keys are set as null for the entities C,D. I can see that 2 sets of update statements are getting fired. First one setting the foreign keys correctly and second one setting the keys to null. And this is not happening for entity B. All of oneToMany relations have { cascade: true, eager: true, onUpdate: "CASCADE", onDelete: "CASCADE" }. Any help to fix this issue will be helpful
The issue is happening because class A is having an attribute, which is the foreign key of table c, referring to corresponding column in table A. We don't have to add the foreign key as a #Column in the child class.
Related
I have schema of
import { Entity, Column, PrimaryColumn } from "typeorm";
#Entity({ name: 'monthly_invoice_rollup' })
export class MonthlyInvoiceRollup {
#PrimaryColumn()
Invoiceno: string;
#Column()
ClientID: string;
#Column()
Rollup_code: string;
#Column()
Rollup_desc: string;
}
I have a class where I set it like
this.monthlyInvoiceRollup = getRepository(MonthlyInvoiceRollup)
and I call it like
const results = await this.monthlyInvoiceRollup.find({
where: { "Invoiceno": "134" },
});
but it only returns the first result in the table even though I know I have multiple results
The design is not correct. By definition: primary key constraint is simply a combination of a unique constraint and a not-null constraint. You can't have multiple entry in the same table with the same primary key. You must find another way to identify multiple entries given a common value. That is why TypeORM returns only one entry: given the primary key there can be only one or zero entry in the DB.
as it is said above the primary key is a combination of unique and not null constraints, in your given example your primary key is invoiceno, foreign key is clientID so your relation is that the client can have 1 or n invoices, invoice related to 1.1 client.
so lets say that ClientID = 134 that can be repeated because it is simply foreign key, so you can lookup your invoices based on the clientID
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
I have 2 domain classes: A and B, defined as follow:
class A {
String data
static hasMany = [bs: B]
}
class B {
String data
static belongsTo = [a: A]
}
Now we have field a_id in table B.
The problem is that I had a_id already, how can I properly insert a new B record with a_id as foreign key?
Currently I did like this:
B b = new B(
data: "data",
a: A.get(a_id)
)
b.save()
=> To be able to insert the B record, I have to do one more query which get the whole A object, such a wasting time & memory since a_id alone is already enough.
Thank you very much.
No way to do that, sadly.
If you want to optimize, consider using B.executeUpdate or even raw SQL
Sql sql = new Sql(dataSource)
sql.executeUpdate("insert into....")
I am trying to access tables in entity framework using another table, but i am getting tables as null.
e.g.
I am having 3 tables A,B and C. And A is having FK(Foreign key) of B and B is having FK of C. I am having object of A. Now I want to access C using B.
means A.B.C.
But i am getting B as null. So please give me the solution for this.
var a= databaseContext.A.Find(Id);
var c=a.B.C.where(x=>x.Id==SomeId);
Thanks in advance.
Update:
Tables
Commitment
CommitmentId(PK)
FinancialYearAccountID(FK)
FinancialYearAccount
FinancialYearAccountId (PK)
AccountId(FK)
Account
AccountId(PK)
Now i want to access Account table from Commitment table
var commitment = databaseContext.Commitments.Find(1);
var account = commitment.FinancialYearAccount.Account.
where(x => x.AccountId==SomeId)
I am getting Commitment Record, but FinancialYearAccount is coming as null, so it is crashing here.
My DB have two tables - Question and Topic. To implement many-to-many relation, there is a mapping table which has following structure:
Table TopicQuestionMapping
int ID (Primary Key)
int QuestionID (Foreign key to Question table)
int TopicID (Foreign key to Topic table)
Now, in my EF I got something like
ViewData.Model = DB.QuestionMaster.Include("TopicQuestionMapping").First(x => x.ID == id);
and then I try to fetch topic like
Model.TopicQuestionMapping.First().TopicMaster.Name
(for simplification, I am just considering the first record)
The query populates the TopicQuestionMapping (I am getting count = 1). But the TopicMaster is null. Howe can I get it work?
It is something like Table A refer to Table B. Table B refer to Table C. I need to get data from Table C.
Include uses .'s to navigate the object graph.
So like .Include("TableA.TableB.TableC")
http://msdn.microsoft.com/en-us/library/bb896272.aspx