Update field(property) in entity - azure-storage

Have i any way update only some fields in my entity?
For example, i want update field Name in entity man, whithout sending full entity.
Now to change the entity I first requested it and after changing the fields, I send this entity to update.

Yes, you can update the entity without updating other properties, by using the Merge Entity or Insert or Merge Entity operation.
Please see our samples for Table storage here. They show how to merge an entity using one of our client libraries.
Here's an excerpt from the .NET sample that may be helpful:
// Create an instance of a customer entity. See the Model\CustomerEntity.cs for a description of the entity.
CustomerEntity customer = new CustomerEntity("Harp", "Walter")
{
Email = "Walter#contoso.com",
PhoneNumber = "425-555-0101"
};
// Demonstrate how to Update the entity by changing the phone number
Console.WriteLine("2. Update an existing Entity using the InsertOrMerge Upsert Operation.");
customer.PhoneNumber = "425-555-0105";
customer = await InsertOrMergeEntityAsync(table, customer);
Also, see the REST API reference for the Merge Entity and Insert or Merge Entity operations:
https://msdn.microsoft.com/en-us/library/azure/dd179392.aspx
https://msdn.microsoft.com/en-us/library/azure/hh452241.aspx

Related

ASP.NET help inserting data into normalized SQL tables best practice

Hi i have a most common situation of inserting a client order into my SQL database. I have created an order header and order detail tables in the db and i am trying to insert a single header record and multiple detail lines corresponding to that header record (the PK and FK constraint is the headerID).
Currently, i insert my header record, then query the db for last created headerID and use that ID to insert my detail lines by looping through grid for example.
I know this is a stupid way for inserting records into normalized tables and there is an extra sql call made, which seems unnecessary. Therefore, would anyone know of a better solution to this problem.
I found that using Entity Framework solves this problem, without making any extra effort to search for the last insert headerid and then insertingit into the detail table. So if relationships are well defined in the Entity Framework, the framework takes care of this process. For Example:
using (var rep = new Repo()){
Header hd = new Header();
hd.name = "some name";
Detail dt = new Detail();
dt.itemname = "some item name";
hd.Details.Add(dt);
rep.Headers.Add(hd);
rep.savechanges();
}
So as long as all the operations are done before the rep.savechanges(); master/detail data will be inserted correctly.
If however, EF finds an integrity error or any other errors, no data will be inserted at all.
So this a nice clean way to insert master/detail data into SQL database.

Entity Framework lookup table

I have 3 tables
Brands:
BrandID int
BrandName varchar(30)
Products
ProdID int
ProdName varchar(30)
BrandToProd:
BrandID int => FK Brands.BrandID
ProdID int => FK Products.ProdID
After generating model from existing database EF omits BrandToProd table and creates Many-To-Many relationships between Brands and Products. I would like to have third entity with following fields:
BrandName varchar(30)
ProductsName varchar(30)
This will give me possibility to use scaffolding for this entity. Ideally, when I'll add new pair of Brand and Product, EF should check first if such Brand or Product already exist in database (to avoid duplicates), if no, add to corresponding tables and that add mapping to BrandToProd table. If Brand or Product already exist, EF should you existing BrandID/ProdID value when adding to BrandToProd table. Is there any idea how to do that?
Your BrandToProd table is a pure junction table, i.e. a table with only two foreign keys. It is an EF feature to model such tables into a many to many association without a class in the conceptual model.
The easiest way to include a pure junction table in the model as an entity class is
add a dummy field to the database table temporarily
generate the model
delete the field from the database
update the model from the database
delete the property in the edmx diagram
An alternative way is to edit the edmx manually, but then you really need to know what you're doing. If you don't want to regenerate the model you could generate a second model and investigate the differences in both edmx files by a difference viewer.
However, I wonder if you need to do this. You seem to relate this to duplicate checking. But if you want to add a Brand or Product to the database you'll have to check for duplicates either way. If you want to add a new association (e.g. adding an existing Brand to Product.Brands) you don't have to check whether it exists. If it does, EF just ignores the "new" association.
As extra point to Gert's answer:
when using surrogate keys, there is always the issue of duplicate management. Normally there is 1 or more fields that make a logical key.
you can
a)create a unique index on the Db. Db will complain when the constraint is violated
b)Execute a logical duplicate check before attempting an insert.
I've ended up with just adding dummy ID field to my junction table, as I'm frequently changing DB schema (becsuse site development is in progress and I need from time to time update model from database) and don't want to each time remove/add dummy field to database. Another option I've used - SQL View on two tables and stored procedures mapped to corresponding actions (CRUD) in EF

NHibernate Hide dummy entity

I'm dealing with a legacy db, which uses dummy records for some empty relations.
Example: article has a relation to supplier. If an article has no supplier, a dummy supplier with ID 0 is assigned to the article, to satisfy the relation between both tables.
When adding a new article via nhibernate, I have to load and assign this dummy supplier to the new article. I would prefer being able to add a new article and leave the supplier field as NULL.
So I'm looking for a solution to transparently transform NULL to this dummy record and vice versa. With help of this question I was able to do the conversion from NULL to the dummy record, but how can I hide the dummy entity in my code?
You can do this by adding a filter to your entities and enable the filter in your session.
nhibernate-filters

How to effectively refresh many to many relationship

Lets say I have entity A, which have many to many relationship with another entities of type A. So on entity A, I have collection of A. And lets say I have to "update" this relationships according to some external service - from time to time I receive notification that relations for certain entity has changed, and array of IDs of current related entities - some relations can be new, some existing, some of existing no longer there... How can I effectively update my database with EF ?
Some ideas:
eager load entity with its related entities, do foreach on collection of IDs from external service, and remove/add as needed. But this is not very effective - need to load possibly hundreds of related entities
clear current relations and insert new. But how ? Maybe perform delete by stored procedure, and then insert by "fake" objects
a.Related.Add(new A { Id = idFromArray })
but can this be done in transaction ? (call to stored procedure and then inserts done by SaveChanges)
or is there any 3rd way ?
Thanx.
Well, "from time to time" does not sound like a situation to think much about performance improvement (unless you mean "from millisecond to millisecond") :)
Anyway, the first approach is the correct idea to do this update without a stored procedure. And yes, you must load all old related entities because updating a many-to-many relationship goes only though EFs change detection. There is no exposed foreign key you could leverage to update the relations without having loaded the navigation properties.
An example how this might look in detail is here (fresh question from yesterday):
Selecting & Updating Many-To-Many in Entity Framework 4
(Only the last code snippet before the "Edit" section is relevant to your question and the Edit section itself.)
For your second solution you can wrap the whole operation into a manually created transaction:
using (var scope = new TransactionScope())
{
using (var context = new MyContext())
{
// ... Call Stored Procedure to delete relationships in link table
// ... Insert fake objects for new relationships
context.SaveChanges();
}
scope.Complete();
}
Ok, solution found. Of course, pure EF solution is the first one proposed in original question.
But, if performance matters, there IS a third way, the best one, although it is SQL server specific (afaik) - one procedure with table-valued parameter. All new related IDs goes in, and the stored procedure performs delete and inserts in transaction.
Look for the examples and performance comparison here (great article, i based my solution on it):
http://www.sommarskog.se/arrays-in-sql-2008.html

Entity Framework 4, POCO, WCF, Updating Many-To-Many

I've got a many-to-many relationship mapped in my Entity Framework POCO classes. In the database it's a join table with a composite key, and the POCO properties are generated fine.
When I load an entity from the context, I can remove an item from the many-to-many collection and the database is updated when I save changes.
For Example:
var item = context.Items.First();
item.OtherItems.Remove(item.OtherItems[0]);
context.SaveChanges();
However, when the detached object graph comes back from WCF, I attach it to the context and mark it as modified. But the changes are not persisted.
Example:
// this happens on the silverlight client
item.OtherItems.Remove(item.OtherItems[0]);
// and on the server
context.Items.Attach(item);
context.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
context.SaveChanges();
In this case the record is not removed from the join table in the database. Any ideas how I can get this to work? Thanks very much in advance.
Changing object state marks your entity modified. You need to use ChangeRelationshipState to mark modified relation between two entities - this will perform DB modification on your join table. You will need to set relation's state as Added or Deleted.