I am struggling to Insert data in a table with Foreign key relationship.I did read a
few articles on how to do this but did not help much and decided to open up a new question.
Scenario :
User table has a foreign key on role table ID.
On the role table Id is integer and is auto incremented
Here is my code,
SalesTrainerEntities db = new SalesTrainerEntities();
var user = new User();
var role = db.Role.FirstOrDefault(r => r.ID == 1);
user.UserName = "test";
user.Pass = "123";
user.CreatedBy = "test";
user.DtCreated = DateTime.Now;
user.Role = role;
//user.RoleId = 1;
//user.EntityKey = new EntityKey("Role", "ID", 1);
//user.RoleReference.EntityKey = new EntityKey("Role", "ID", 1);
db.AddToUser(user);
db.SaveChanges();
On Save Changes I get error stating
Unable to update the EntitySet 'User' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
Any pointers will be highly appreciated.
Regards,
Sab
I used to add children entities this way, I'm assuming a relation 1:N between user and role.
using (Entities db = new Entities())
{
var user = new User();
// fill user data..
var newRole = db.Role.FirstOrDefault(r => r.ID == 1);
if(newRole!=null)
{
user.roles.AddObject(newRole);
db.users.AddObject(user);
db.SaveChanges();
}
}
//Edit - Updating db
using (Entities db = new Entities())
{
var existingUser = db.User.FirstOrDefault(r => r.ID == 100);
if(existingUser !=null)
{
existingUser.Name = "New name";
db.SaveChanges();
}
}
Related
So, I'm trying to update rows where LOGIN IS NULL and ID = 1. If there are no rows with these parameters then add new row. I use attach to make that in 1-2 queries so I'm trying to avoid SELECT first and then update.
Problem in NULL value. EF simply ignores LOGIN since it has null value, however I need to find only rows where LOGIN IS NULL. Can I solve that problem without additional SELECT query?
My code:
using (var db = new EntityContext())
{
var ent = new Entity { ID = 1, LOGIN = null };
db.Entities.Attach(ent);
ent.LOGIN = "Whatever";
ent.EMAIL = "Whatever";
int count = db.SaveChanges();
if (count == 0)
{
var clone_ent = new Entity { LOGIN = "Whatever", PASS = "Whatever" };
db.Entities.Add(clone_ent);
db.SaveChanges();
}
}
SQL analog:
UPDATE Entities SET LOGIN = #LOGIN, EMAIL = #EMAIL
WHERE ID = 1 AND LOGIN IS NULL
IF ##ROWCOUNT = 0
INSERT INTO Entities (LOGIN, EMAIL)
VALUES #LOGIN, #EMAIL
Unfortunately, it is not possible to include a WHERE condition into UPDATE statements in entity framework so you will have to select, then update or insert, e.g.:
using (var db = new EntityContext())
{
var ent = db.Entities.Where(x => x.ID == 1 && x.LOGIN == null).FirstOrDefault();
if (ent != null)
{
ent.LOGIN = "Whatever";
ent.EMAIL = "Whatever";
}
else
{
db.Entities.Add(ent);
}
db.SaveChanges();
}
I'm somewhat new to EF 6.0 so I'm pretty sure I'm doing something wrong here.
there are two questions related to the problem
what am I doing wrong here
what's the best practice to achieve this
I'm using a code first model, and used the edmx designer to design the model and relationships, the system needs to pull information periodically from a webservice and save it to a local database (SQL Lite) in a desktop application
so I get an order list from the API, when I populate and try to save Ticket, I get a duplicate key exception when trying to insert TicketSeatType -
how do I insert the ticket to dbContext, so that It doesn't try and re-insert insert TicketSeatType and TicketPriceType, I have tried setting the child object states to unchanged but it seems to be inserting
secondly, what would be the best practice to achieve this using EF ? it just looks very inefficient loading each object into memory and comparing if it exists or not
since I need to update the listing periodically, I have to check against each object in the database if it exists, then update, else insert
code:
//read session from db
if (logger.IsDebugEnabled) logger.Debug("reading session from db");
dbSession = dbContext.SessionSet.Where(x => x.Id == sessionId).FirstOrDefault();
//populate orders
List<Order> orders = (from e in ordersList
select new Order {
Id = e.OrderId,
CallCentreNotes = e.CallCentreNotes,
DoorEntryCount = e.DoorEntryCount,
DoorEntryTime = e.DoorEntryTime,
OrderDate = e.OrderDate,
SpecialInstructions = e.SpecialInstructions,
TotalValue = e.TotalValue,
//populate parent refernece
Session = dbSession
}).ToList();
//check and save order
foreach (var o in orders) {
dbOrder = dbContext.OrderSet.Where(x => x.Id == o.Id).FirstOrDefault();
if (dbOrder != null) {
dbContext.Entry(dbOrder).CurrentValues.SetValues(o);
dbContext.Entry(dbOrder).State = EntityState.Modified;
}
else {
dbContext.OrderSet.Add(o);
dbContext.Entry(o.Session).State = EntityState.Unchanged;
}
}
dbContext.SaveChanges();
//check and add ticket seat type
foreach (var o in ordersList) {
foreach (var t in o.Tickets) {
var ticketSeatType = new TicketSeatType {
Id = t.TicketSeatType.TicketSeatTypeId,
Description = t.TicketSeatType.Description
};
dbTicketSeatType = dbContext.TicketSeatTypeSet.Where(x => x.Id == ticketSeatType.Id).FirstOrDefault();
if (dbTicketSeatType != null) {
dbContext.Entry(dbTicketSeatType).CurrentValues.SetValues(ticketSeatType);
dbContext.Entry(dbTicketSeatType).State = EntityState.Modified;
}
else {
if (!dbContext.ChangeTracker.Entries<TicketSeatType>().Any(x => x.Entity.Id == ticketSeatType.Id)) {
dbContext.TicketSeatTypeSet.Add(ticketSeatType);
}
}
}
}
dbContext.SaveChanges();
//check and add ticket price type
foreach (var o in ordersList) {
foreach (var t in o.Tickets) {
var ticketPriceType = new TicketPriceType {
Id = t.TicketPriceType.TicketPriceTypeId,
SeatCount = t.TicketPriceType.SeatCount,
Description = t.TicketPriceType.Description
};
dbTicketPriceType = dbContext.TicketPriceTypeSet.Where(x => x.Id == ticketPriceType.Id).FirstOrDefault();
if (dbTicketPriceType != null) {
dbContext.Entry(dbTicketPriceType).CurrentValues.SetValues(ticketPriceType);
dbContext.Entry(dbTicketPriceType).State = EntityState.Modified;
}
else {
if (!dbContext.ChangeTracker.Entries<TicketPriceType>().Any(x => x.Entity.Id == ticketPriceType.Id)) {
dbContext.TicketPriceTypeSet.Add(ticketPriceType);
}
}
}
}
dbContext.SaveChanges();
//check and add tickets
foreach (var o in ordersList) {
dbOrder = dbContext.OrderSet.Where(x => x.Id == o.OrderId).FirstOrDefault();
foreach (var t in o.Tickets) {
var ticket = new Ticket {
Id = t.TicketId,
Quantity = t.Quantity,
TicketPrice = t.TicketPrice,
TicketPriceType = new TicketPriceType {
Id = t.TicketPriceType.TicketPriceTypeId,
Description = t.TicketPriceType.Description,
SeatCount = t.TicketPriceType.SeatCount,
},
TicketSeatType = new TicketSeatType {
Id = t.TicketSeatType.TicketSeatTypeId,
Description = t.TicketSeatType.Description
},
Order = dbOrder
};
//check from db
dbTicket = dbContext.TicketSet.Where(x => x.Id == t.TicketId).FirstOrDefault();
dbTicketSeatType = dbContext.TicketSeatTypeSet.Where(x => x.Id == t.TicketSeatType.TicketSeatTypeId).FirstOrDefault();
dbTicketPriceType = dbContext.TicketPriceTypeSet.Where(x => x.Id == t.TicketPriceType.TicketPriceTypeId).FirstOrDefault();
if (dbTicket != null) {
dbContext.Entry(dbTicket).CurrentValues.SetValues(t);
dbContext.Entry(dbTicket).State = EntityState.Modified;
dbContext.Entry(dbTicket.Order).State = EntityState.Unchanged;
dbContext.Entry(dbTicketSeatType).State = EntityState.Unchanged;
dbContext.Entry(dbTicketPriceType).State = EntityState.Unchanged;
}
else {
dbContext.TicketSet.Add(ticket);
dbContext.Entry(ticket.Order).State = EntityState.Unchanged;
dbContext.Entry(ticket.TicketSeatType).State = EntityState.Unchanged;
dbContext.Entry(ticket.TicketPriceType).State = EntityState.Unchanged;
}
}
}
dbContext.SaveChanges();
UPDATE:
Found the answer, it has to do with how EF tracks references to objects, in the above code, I was creating new entity types from the list for TicketPriceType and TicketSeatType:
foreach (var o in ordersList) {
dbOrder = dbContext.OrderSet.Where(x => x.Id == o.OrderId).FirstOrDefault();
foreach (var t in o.Tickets) {
var ticket = new Ticket {
Id = t.TicketId,
Quantity = t.Quantity,
TicketPrice = t.TicketPrice,
TicketPriceType = new TicketPriceType {
Id = t.TicketPriceType.TicketPriceTypeId,
Description = t.TicketPriceType.Description,
SeatCount = t.TicketPriceType.SeatCount,
},
TicketSeatType = new TicketSeatType {
Id = t.TicketSeatType.TicketSeatTypeId,
Description = t.TicketSeatType.Description
},
Order = dbOrder
};
....
in this case the EF wouldn't know which objects they were and try to insert them.
the solution is to read the entities from database and allocate those, so it's referencing the same entities and doesn't add new ones
foreach (var t in o.Tickets) {
//check from db
dbTicket = dbContext.TicketSet.Where(x => x.Id == t.TicketId).FirstOrDefault();
dbTicketSeatType = dbContext.TicketSeatTypeSet.Where(x => x.Id == t.TicketSeatType.TicketSeatTypeId).FirstOrDefault();
dbTicketPriceType = dbContext.TicketPriceTypeSet.Where(x => x.Id == t.TicketPriceType.TicketPriceTypeId).FirstOrDefault();
var ticket = new Ticket {
Id = t.TicketId,
Quantity = t.Quantity,
TicketPrice = t.TicketPrice,
TicketPriceType = dbTicketPriceType,
TicketSeatType = dbTicketSeatType,
Order = dbOrder
};
...}
Don't you think that you are trying to write very similar codes for defining the state of each entity?
We can handle all of these operations with a single command.
You can easily achieve this with the newly released EntityGraphOperations for Entity Framework Code First. I am the author of this product. And I have published it in the github, code-project (includes a step-by-step demonstration and a sample project is ready for downloading) and nuget. With the help of InsertOrUpdateGraph method, it will automatically set your entities as Added or Modified. And with the help of DeleteMissingEntities method, you can delete those entities which exists in the database, but not in the current collection.
// This will set the state of the main entity and all of it's navigational
// properties as `Added` or `Modified`.
context.InsertOrUpdateGraph(ticket);
By the way, I feel the need to mention that this wouldn't be the most efficient way of course. The general idea is to get the desired entity from the database and define the state of the entity. It would be as efficient as possible.
I have a problem saving my data in Entity Framework.
I have done a function that overrides the saveChanges of my dbContext, because I use it to set some audit data and do other stuff. In one case I have a big trouble.
I have to insert, for each new record, some records in another table, referring to the new with a foreign key. If the new record is only one, it is all ok. But if the record are 2 or more, I get errors.
I have a for, looping on all the new records, in this way:
var addedAuditedEntities = ChangeTracker.Entries()
.Where(p => p.State == EntityState.Added)
.Select(p => p.Entity);
foreach (var added in addedAuditedEntities)
{
.....
}
I write my attempts.
1) in this way, it gives error at the second new record, saying that there is already an unique data in the tab TabAssVeicoliTerminali (it is a table with an unique index on the couple IDTER-IDTEV), I think because it inserts temporary all records with IDTEV = 0
else if (added.GetType() == typeof(TabTessereVeicoli))
{
TabTessereVeicoli i = (TabTessereVeicoli)added;
i.DATA_INS = now;
i.USER_INS = mdlImpostazioni.p.UserName;
var listaterV = new List<TabAssVeicoliTerminali>();
foreach (var ter in MainWindow.dbContext.TabTerminali)
{
var tt = new TabAssVeicoliTerminali();
tt.MODIFICATO = true;
tt.ABILITATO = true;
tt.IDTER = ter.ID;
tt.IDTEV = i.ID;
tt.DATA_INS = now;
tt.USER_INS = mdlImpostazioni.p.UserName;
listaterV.Add(tt);
}
MainWindow.dbContext.BulkInsert(listaterV);
}
2) So, I tried to save before, to try to set the ID of the new record (it is autoincremental id) and use something != 0 in the IDTEV foreign key. But, it saves all, also the other new records. So, it saves correctly the fk in other table, but only for the first new record:
else if (added.GetType() == typeof(TabTessereVeicoli))
{
TabTessereVeicoli i = (TabTessereVeicoli)added;
i.DATA_INS = now;
i.USER_INS = mdlImpostazioni.p.UserName;
var listaterV = new List<TabAssVeicoliTerminali>();
base.SaveChanges();
foreach (var ter in MainWindow.dbContext.TabTerminali)
{
var tt = new TabAssVeicoliTerminali();
tt.MODIFICATO = true;
tt.ABILITATO = true;
tt.IDTER = ter.ID;
tt.IDTEV = i.ID;
tt.DATA_INS = now;
tt.USER_INS = mdlImpostazioni.p.UserName;
listaterV.Add(tt);
}
MainWindow.dbContext.BulkInsert(listaterV);
}
3) I have also tried without the BulkInsert, but I get the same results.
How can I reach my goal?
Starting from the hint of Ben Robinson in the comments of this question, I have found a solution.
It works, but it stil is the "perfect solution", because to do it, I had to comment the part of the bulk insert, so it is a bit slow with a lot of new records.
Anyway, the code I have posted in the question, is now:
else if (added.GetType() == typeof(TabTessereVeicoli))
{
TabTessereVeicoli i = (TabTessereVeicoli)added;
i.DATA_INS = now;
i.USER_INS = mdlImpostazioni.p.UserName;
var listaterV = new List<TabAssVeicoliTerminali>();
foreach (var ter in MainWindow.dbContext.TabTerminali)
{
var tt = new TabAssVeicoliTerminali();
tt.MODIFICATO = true;
tt.ABILITATO = true;
tt.IDTER = ter.ID;
tt.IDTEV = i.ID;
tt.DATA_INS = now;
tt.USER_INS = mdlImpostazioni.p.UserName;
//listaterV.Add(tt);
i.TabAssVeicoliTerminali.Add(tt);
}
//MainWindow.dbContext.BulkInsert(listaterV);
}
Let me know if you know how can I reach my goal using also the bulkInsert!
I have a LINQ To Sql data context, with a mapping to tables User and Group. A user belongs to a Group.
So I would like to get the corresponding SQL generated for Insert/Update by data context against a particular entity.
For e.g.
using (var context = new TestBedDataContext())
{
using (var trans = new TransactionScope())
{
context.Users.InsertOnSubmit(new User
{
Name = "Test",
Password = "Password",
Username = "test",
Group1 = new Group
{
Name = "Group1"
}
});
// Get the query for User entity
}
}
Here I would like to get the queries that will be generated for inserting a new user along with Group entity.
I know context.Log property can be used to capture the entire SQL generated, the problem with that approach is, it will catch all the SQL which are not in my interests (like change scripts for some other entities)
public void addPatientInformation() {
using(DbClassesDataContext myDb = new DbClassesDataContext()) {
myDb.PatientInfos.InsertOnSubmit(new PatientInfo {
Phy_ID = physcianID,
Pat_First_Name = txtFirstName.Text,
Pat_Middle_Init = txtMiddleName.Text,
Pat_Last_Name = txtLastName.Text,
Pat_Gender = cmbGender.Text,
Pat_Marital_Status = cmbMaritalStatus.Text,
Pat_Date_Of_Birth = dtpDOB.Value,
Pat_Home_Add = txtHomeAdd.Text,
Pat_Home_Num = txtPhone.Text,
Pat_Work_Add = txtWorkAdd.Text,
Pat_Work_Num = txtWorkPhone.Text,
Pat_Prim_Physician = txtPrimPhysician.Text,
Pat_Ref_Physician = txtRefePhysician.Text,
});
myDb.SubmitChanges();
}
}
I have 2 tables Users and Queries. They are connected via FK(UserId) in Queries table.
I need to add queries added, for example, by user with login "Bob" to all users.
Here is a chunk of code i'm using:
public bool SaveUserQuery(string userName, Query query) {
var db = new UserDataClassesDataContext();
Table<User> users = db.Users;
if ( userName.ToLower() == "bob" ) {
foreach ( var user in users ) {
var tempQuery = new Query();
tempQuery.Name = query.Name;
tempQuery.FolderName = query.FolderName;
tempQuery.Layout = query.Layout;
tempQuery.Description = query.Description;
tempQuery.Query1 = query.Query1;
tempQuery.UserID = user.UserId;
try {
user.Queries.Add(q);
}
catch (Exception e) {
Logger.Log.Error("attach", e);
}
}
db.SubmitChanges();
return true;
}
}
It throws error when adding:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Queries_Users". The conflict occurred in database "OLAPUsers", table "dbo.Users", column 'UserId'.
How can i fix this or archive the goal i have?
Make sure that your primary keys are setup correctly in the DB schema. You can query tables without primary keys, but you can't do inserts unless everything is setup correctly, and the data context's view of the DB is current.
Try this:
public bool SaveUserQuery(string userName, Query query)
{
var db = new DataContext();
if ( userName.ToLower() == "bob" )
{
List<Query> queries = new List<Query>();
foreach ( var user in db.GetTable<Users>())
{
Query tempQuery = new Query(query.Name, query.FolderName, query.Layout, query.Description, query.Query1, user.UserId);
//and ofc create this constructor
queries.Add(tempQuery);
}
db.GetTable<Query>().InsertAllOnSubmit(queries);
db.SubmitChanges();
return true;
}
}