EF6 Updating 3 tables in one go - c#

I have a database with 3 tables
Table
Customer
CustomerID (PK)
Name
Table
Order
OrderID (PK)
CustomerID (FK)
OrderDate
Table
OrderDetailLine
OrderDetailLineID
OrderID (FK)
Price
ProductCode
What I would like to do in the Entity Framework is add 1 customer, then add several different Orders, each with many OrderDetailLine all relating to the first customer inserted. I have hooked up all the relationship in SQL Server and imported them into EF model. All no problems. I can insert 1 customer and many orders and OrderDetailLine first time all records get inserted ok into the correct databse tables
I am looping around customer and orders in a file adding then adding the customer and orders to the database
But when I want to add another order for the same customer( I am getting a Primary key violation on Customer with CustomerID). EF is trying to re-insert the same customer after my initial context.SaveChanges();
So, how do I stop EF from trying to add the same customer when using the same datacontext?
I have been going around in circles for hours and getting the same error
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_Order_Customer\". The conflict occurred in database \"xxxxx\", table \"dbo.Customer\", column 'CustomerID'
The customer is newly created along with the order and orderlines. But it works first time and I get the CustomerID back from EF. But when I add new order and orderlines after the inital context.savechanges(); I get the FK error

Thanks for taking the time.
The problem was I was just calling DataContext.SaveChanges() with adding the entities to the correct model. For example:
Customer.Order.Add(customerInfo);
Well it was my lack of understanding.

Related

In SQL, how to remove from only 1 table from 2 related tables

I have related tables in SQL (one to many). One is employees table and the other is the record table for day offs, When i want to delete one employee I get the below error in C#:
SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_Izin_Personel". The conflict occurred in database "Inotra", table "dbo.Izin", column 'personelid'.
The statement has been terminated.
I tried changing insert and update actions to cascade and that worked for other tables, but it also deletes from both tables when I delete from one.
So my question is: How can I remove from only one of the two related tables, so that the records of other table remain unchanged?
When you delete from the employee table, then you must also delete all related records in the record table.
Relationships ensure data integrity, without them, data may be incomplete or incorrect. In your case you need to remove the relationship between the tables("FK_Izin_Personel"), then there will be no error.

Entity Framework - trying to insert into a table with a foreign key, EF attempts to insert into the original table with the primary key

Hi, there's my Database diagram.
I'm trying to insert rows into Order and OrderItem tables. Insertion into Order table goes fine.
However, when I'm trying to insert into OrderItem table I get an exception. Cannot insert into Product table, ProductId already exists. Why does this happen?
Insert code:
db.Orders.Add(newOrder);
db.SaveChanges();
newOrder.OrderItems = products.Convert(newOrder);
foreach (var orderItem in newOrder.OrderItems)
{
db.OrderItems.Add(orderItem);
}
db.SaveChanges();
New order object already has a list of order items, and I need only an exception (for productId) if OrderItem record I want to insert doesn't have existing productId in product table, not insert into Product table. How is this fixable ?
Cross check whether the list of order items has Product entity object as it is a foreign key for the OrderItem table. Also you can try inserting explicitly in child tables like first insert into Order then Order Items taking the Order entity object this should work (Note OrderItem should have Product entity object).

Manual Entity Framework association

I have the following tables:
Table Group (
id INT PK,
year INT PK,
name VARCHAR
)
Table Person (
id PK,
GroupID INT,
name VARCHAR
)
The database does not have foreign keys defined so I want to create a manual association from the Person tables GroupID to the Group tables id.
To do this I right click Person and Add an association. I create a Many to One association and everything works. The problem is when I go to add the mapping. Because the Group table has two primary keys entity framework was something from the Person table to map to the year key.
What do I need to do to create the association?
You cannot create such association because EF follows same rules as database. All PK columns from principal entity must exists as FK columns in dependent entity.
The only way can be some database view selecting distinct Groups with Id and Name and mapped as read only entity and build navigation between those two. I didn't try it but I guess it should work. It will have its own disadvantages because you will have two completely unrelated entities for group and the entity related to person will not accept any modification (without mapping custom SQL commands or stored procedures to insert, updated and delete operations).

Problem regarding Many to Many relationship in EF code first

I have Products table and Customers table. Thus there is many to many relationship between them. This is my code to create that relationship using ModelBuilder:
modelBuilder.Entity<Customer>().
HasMany(c => c.ProductsPurchased).
WithMany(p => p.Customers).Map(m =>
m.MapLeftKey("CustomerId").
MapRightKey("ProductId").
ToTable("CustomersXProducts"));
Problem here is the Join table contains primary key of CustomerId and ProductId. This essentially means one customer can purchase the same product only one time. How can I resolve this issue? I don't want CustomerId to be a primary key in my join table.
You cannot resolve the issue with your database. You generally need some additional unique column to be primary key of your junction table or you need some addition data column to form composite key with both CustomerId and ProductId. That will lead to change in your model. You will need to expose junction table as an entity - Customer and Product entities must be related to the new entity.
Perhaps you will need this anyway. It is not very common to have such relation without any additional data. Perhaps your model needs bigger change. For example customer tracking system usually uses some form of entities like Customer, Order, OrderItem, Product so there is no relation between Customer and Product directly.

EF model from 2 tables connected with junction table - Model don't see records and changes in junction table

I have several tables in my SQL2008 DB, Managers(ManagerID is a PK, incremental) and Customers(CustomerID is a PK, incremental) are among them. All ID columns are int. They are connected with junction table ManagersCustomers(fields: CustomerID is a PK, ManagerID) and there are relations: from CustomerID in Customers to same in junction table with delete cascade rule and from ManagerID in Managers to same in junction table with delete cascade too. So I have Managers 0..1 to * Customers relation in my edmx model after generating it from my DB and I can see this relation is mapped to junction table. I tested junction table in SQL Server Management Studio, it works correctly. Ok.
In my app I have 2 parts - edmx model on server side connected with client side through WCF Data Service. In client part I'm creating instance of my entities class, and in debug mode I can watch entities class instance's data. Both entities Customers and Managers are filled with data correctly, but in navigation fields I can see only 0. For example I have Customer with CustomerID = 1 connected with Manager with ManagerID=3 and there is a record in junction table. So, if it would work correctly, I would see my manager in navigation field of Customers entity and same with customer nav field in Managers entity. But I can see only zeros.
The easiest thing to do is to change the ManagersCustomers table so that both columns are part of the PK, and then recreate your model. The GUI designer won't pick it up as a many-to-many association unless you do.

Categories