Adding an entity to the Breeze saveMap which comes from DB (not a totally new entity) - entity-framework

I use Breeze in my asp.net application with the Durandal SPA template.
I need to add an entity to the saveMap which already exists in DB.
Let's take this simple example: the page display an invoice and the invoice's lines. The user add a new invoice's line and click the save button. The SaveChanges controller's action is triggered with ONLY the modified invoice's line. Server side, the total is recalculated and the invoice's total must be modified. But this total is located on the invoice entity so we need to add the invoice's entity to the saveMap.
I found a way to proceed to add a new entity to the saveMap here: Breeze BeforeSaveEntities: how to modify savemap
But the suggested solution is used to add a new entity to the saveMap (Added state) which will create a new record on DB. This is not what I need. I need to add a new entity to the saveMap which (Modified state) will be get the data from DB.
I tried like this:
int invoiceId = 1234;
dc.Configuration.ProxyCreationEnabled = false; // don't forget this!
EFContextProvider<BreezeContext> cp = new EFContextProvider<BreezeContext>();
var acc = dc.Invoices.Where(x => x.Id == invoiceId).FirstOrDefault();
ei = cp.CreateEntityInfo(acc, Breeze.WebApi.EntityState.Modified);
invoices = new List<EntityInfo>();
saveMap.Add(typeof(Invoice), invoices);
invoices.Add(ei);
So far so good.
Then I need to add the total property to the OriginalValuesMap (otherwise modification will not be updated):
ei.OriginalValuesMap.Add("TotalExclVAT", invoice.TotalExclVAT);
**This don't work: ei.OriginalValuesMap is null and so I cannot add a new key inside.
I don't know if this is the right way to proceed. Hope my explanations are clear enough.
Thanks for your help.
UPDATE
As suggested by Jay:
ei.ForceUpdate = true;
No need to take care of OriginalValuesMap in this case.

I haven't yet had a chance to dig into this yet, but have you looked at the EntityInfo.ForceUpdate property.
This property may be used to force a server side update of an entire entity when server side modification has been made to an existing entity. May be used in place of explicitly updating the EntityInfo.OriginalValuesMap.
So far we've only documented this in the release notes so it's understandable how it might be missed.

Related

Entity Framework 4.1: HOWTO know the next identifier assigned by Database automatically

I have POCO objects which their identifiers are unique and generated automatically by the database, so the problem is when you want to know for some reason which will be the next identifier that the database is going to assign to the next record you are inserting. As far as I know it is only possible after performin dbContext.SaveChanges() so I would like to know if I am right or is there a way to know the next identifier assigned by database automatically.
is there a way to know the next identifier assigned by database
automatically
Well, the next one NO. And if your code depends on it, you really need to change your design.
If you need the identifier to insert related objects, you should check some other questions because you can assign entities to eachother instead of ID's and it will be fine.
I agree with the general purport of the comments that having to know an identity value is "smelly". But on the other hand sometimes you have to live with a given design.
You can't really get the value of the next id, but you can get the value of the assigned id in time by using a TransactionScope.
using (var trans = new TransactionScope())
{
// Create new object
...
context.SaveChanges();
int id = newEntity.Id;
dependentEntity.IdString = string.Format("{0:0000000}", id);
context.SaveChanges();
trans.Complete();
}

Entity Framework 5 Foreign Key New Record on SaveChanges

I'm using .NET4.5/EF5 and have created the model from an existing database.
I'm using the following code:
Order currentOrder = new Order();
using (var db = new ILSEntities())
{
try
{
Event currentEvent = db.Events.OrderByDescending(u => u.EventID).FirstOrDefault();
currentOrder.Event = currentEvent;
db.Orders.Add(currentOrder);
db.SaveChanges();
And I'm seeing that a duplicate record is being created of the Event object I find, which is not what I wanted to happen.
I've read a lot of posts relating to similar problems, but where the context of the two participants in the foreign key relationships are different. Here, I'm saving with the same context I use to find one, and the other object is new.
I've also tried:
currentOrder.Event.EventID = currentEvent.EventID;
but that fails as well as I get an EF validation error telling me it needs values for the other members of the Event object.
I've also tried specifically setting the EntityState of the object being duplicated to Detached, Modified etc. after adding the Order object but before SaveChanges without success.
I'm sure this is a basic problem, but it's got me baffled
In my understanding, both parent and child objects have to be in the context before you assign any relationship between them to convince the entity framework that an entity exists in the database already. I guess you are trying to add new Order object to Database, to add new object you should be using AddObject method, Add() method is used to establish relation between entitties. In your code, currentOrder is not in the context. Try to hook it in the same context and then assign a relation. Your code should look like this :
Order currentOrder = new Order();
using (var db = new ILSEntities())
{
try
{
Event currentEvent = db.Events.OrderByDescending(u => u.EventID).FirstOrDefault();
db.Orders.Attach(currentOrder); //attach currentOrder to context as it was not loaded from the context
currentOrder.Events.Add(currentEvent);//establish relationship
db.ObjectStateManager.ChangeObjectState(currentOrder, EntityState.Added);
db.SaveChanges();
}
}
OK, I did in the end figure this out, and it was my fault.
The problem was that the Order object is FK'd into another table, Shipments, which is also FK'd into Events. The problem was that it was the Event reference in the Shipment object that was causing the new record. The solution was to let EF know about these relationships by adding them all within the same context.
The code assembling the object graph was spread over a number of webforms and the responses here made me take a step back and look at the whole thing critically so whilst no one of these answers is correct, I'm voting everybody who replied up

Entity framework: how to read current data after delete from referenced table

I have three tables Job, Contact and a reference table between them named JobContact. When I delete a record from JobContact table, so record is deleted from database, but it is still present in code. I mean, when I do a select Job by key and when I'm accessing job.JobContact, so record is still there.
How can I force EF to get the current data from this table?
Edited:
I'm using EF to delete the record. Here is a code sample how I'm doing it:
Step 1: delete record from JobContact:
var jobContactRepos = RepositoryFactory.GetRepository<JobContact>();
var jobContact = jobContactRepos.SelectByKey(jobContactId);
jobContactRepos.Delete(jobContact);
jobContactRepos.Save();
Step 2: get the job record from DB after step 1 is done:
var jobRepos = RepositoryFactory.GetRepository<Job>();
var job = jobRepos.SelectByKey(id);
After Step 1, record is deleted from DB: it is OK.
After Step 2, record is still present in the job.JobContact entity: it is not OK.
RepositoryFactory creates already a new context. So I don't understant. In which place in my code should I use Refresh() method?
thanks
You can dispose your EF context and create a new one, this will force EF to get fresh data from the DB instead of using possibly cached data. Alternatively you can call Refresh() on your context using RefreshMode.StoreWins.
But the real question is why do you delete this record from the database directly and don't use EF for it? Had you used the EF context to remove the Contact entity from the Contacts navigation property collection of your Job entity, this problem shouldn't be there in the first place.
Edit:
The reference table should be represented in EF as a navigation property Contacts in your Job entities, and a navigation property Jobs in your Contact entities. Are you using an older version of EF (I am probably not familiar enough with previous versions) or have a custom repository layer that introduces this reference entity?

Entity Framework / EF4: Multiple inserts of related entities in a transactionscope

I have a similar problem.
I want to make two inserts in the same transactionscope. The objects are related and have a FK relationship between them, but for several reasons I do not want to connect them via the navigation property, but only by ID.
This is a simplification of what I what I want to accomplish:
Order o = new Order();
OrderDetails d = new OrderDetails();
new Repository().SaveNew(o, d);
class Repository{
void SaveNew(Order o, OrderDetails d){
using (TransactionScope transaction = new TransactionScope())
{
_context.Connection.Open();
// order
_context.Orders.ApplyChanges(o);
_context.SaveChanges();
// details
d.OrderID = o.ID;
_context.OrderDetails.ApplyChanges(d);
_context.SaveChanges(); <--- UpdateException
_context.Connection.Close();
transaction.Complete();
}
}
}
The problem is that I get an UpdateException because the FK evaluation fails. I tried to remove the FK relationship and running the exact same piece of code, and it worked fine, and both objects had the right properties set. So why does this approach fail? And how should this instead be done? Again, I do not want to attach the entites via their navigation properties.
Thank you!
I would leave the FK relationship in the database, but delete the AssociationSet and Association from the SSDL. The designer won't let you do this, you have to edit the XML manually.
I am using EF 4 btw.
Then use AddObject and SaveChanges in your SaveNew method to add the first (parent) object. Set the foreign key Property on the child and add it with AddObject and SaveChanges.
I do not have development environment running to test this, but what I think is happening is:
Assuming that the id is generated in the database. At the point when you save the order you do not know the ID.
Then the order ID of the order detail is set to the ID of the order, but the order was not reloaded from the database. I suspect that the value is 0.
When you try to save the order detail with FK of 0, you get an error.
Either save both at the same time so that EF does the work for you, or reload the order.

Adding & Removing Associations - Entity Framework

I'm trying to get to grips with EF this week and I'm going ok so far but I've just hit my first major snag. I have a table of items and a table of categories. Each item can be 'tagged' with many categories so I created a link table. Two columns, one the primary ID of the item, the other the primary ID of the category. I added some data manually to the DB and I can query it all fine through EF in my code.
Now I want to 'tag' a new item with one of the existing categories. I have the category ID to add and the ID of the Item. I load both as entities using linq and then try the following.
int categoryToAddId = Convert.ToInt32(ddlCategoriesRemaining.SelectedValue);
var categoryToAdd = db.CollectionCategorySet.First(x => x.ID == categoryToAddId);
currentCollectionItem.Categories.Add(categoryToAdd);
db.SaveChanges();
But I get "Unable to update the EntitySet 'collectionItemCategories' because it has a DefiningQuery and no element exists in the element to support the current operation."
Have I missed something? Is this not the right way to do it? I try the same thing for removing and no luck there either.
I think I have managed to answer this one myself. After alot of digging around it turns out that the Entity Framework (as it comes in VS2008 SP1) doesn't actually support many to many relationships very well. The framework does create a list of objects from another object through the relationship which is very nice but when it comes to adding and removing the relationships this can't be done very easily. You need to write your own stored procedures to do this and then register them with Entity Framework using the Function Import route.
There is also a further problem with this route in that function imports that don't return anything such as adding a many to many relationship don't get added to the object context. So when your writing code you can't just use them as you would expect.
For now I'm going to simply stick to executing these procedures in the old fashioned way using executenonquery(). Apparently better support for this is supposed to arrive in VS2010.
If anyone feels I have got my facts wrong please feel free to put me right.
After you have created your Item object, you need to set the Item object to the Category object on the Item's Categories property. If you are adding a new Item object, do something like this:
Using (YourContext ctx = new YourContext())
{
//Create new Item object
Item oItem = new Item();
//Generate new Guid for Item object (sample)
oItem.ID = new Guid();
//Assign a new Title for Item object (sample)
oItem.Title = "Some Title";
//Get the CategoryID to apply to the new Item from a DropDownList
int categoryToAddId = Convert.ToInt32(ddlCategoriesRemaining.SelectedValue);
//Instantiate a Category object where Category equals categoryToAddId
var oCategory = db.CategorySet.First(x => x.ID == categoryToAddId);
//Set Item object's Categories property to the Category object
oItem.Categories = oCategory;
//Add new Item object to db context for saving
ctx.AddtoItemSet(oItem);
//Save to Database
ctx.SaveChanges();
}
Have you put foreign keys on both columns in your link table to the item and the category or defined the relationship as many to many in the Mapping Details?