Entity Framework update issue - asp.net

I am not sure if it's a bug, but when i add a new view or a new stored procedure to the model it updates all the tables that exist. So my question is should it work like this and if it should how can i add some new procedure without updating the whole model?

Yes, this is the correct functionality when using the "Update Model" function for EntityFramework. It looks at every database object and updates the EF Model to match what it finds in the database. This is, in part, because the designer does not let you specifically choose which tables or view to update, so it verifies any changes in the database. This allows the model to proactively ensure that when it connects to the database there won't be an error based on the database changing.

Related

LINQ to SQL - updating records

Using asp.net 4 though C#.
In my data access layer I have methods for saving and updating records. Saving is easy enough but the updating is tedious.
I previously used SubSonic which was great as it had active record and knew that if I loaded a record, changed a few entries and then saved it again, it recognised it as an update and didn't try to save a new entry in the DB.
I don't know how to do the same thing in LINQ. As a result my workflow is like this:
Web page grabs 'Record A' from the DB
Some values in it are changed by the user.
'Record A' is passed back to the data access layer
I now need to load Record A again, calling it 'SavedRecord A', update all values in this object with the values from the passed 'Record A' and then update/ save 'SavedRecord A'!
If I just save 'Record A' I end up with a new entry in the DB.
Obviously it would be nicer to just pass Record A and do something like:
RecordA.Update();
I'm presuming there's something I'm missing here but I can't find a straightforward answer on-line.
You can accomplish what you want using the Attach method on the Table instance, and committing via the SubmitChanges() method on the DataContext.
This process may not be as straight-forward as we would like, but you can read David DeWinter's LINQ to SQL: Updating Entities for a more in depth explanation/tutorial.
let's say you have a product class OR DB, then you will have to do this.
DbContext _db = new DbContext();
var _product = ( from p in _db.Products
where p.Id == 1 // suppose you getting the first product
select p).First(); // this will fetch the first record.
_product.ProductName = "New Product";
_db.SaveChanges();
// this is for EF LINQ to Objects
_db.Entry(_product).State = EntityState.Modified;
_db.SaveChanges();
-------------------------------------------------------------------------------------
this is another example using Attach
-------------------------------------------------------------------------------------
public static void Update(IEnumerable<Sample> samples , DataClassesDataContext db)
{
db.Samples.AttachAll(samples);
db.Refresh(RefreshMode.KeepCurrentValues, samples)
db.SubmitChanges();
}
If you attach your entities to the context and then Refresh (with KeepCurrentValues selected), Linq to SQL will get those entities from the server, compare them, and mark updated those that are different
When LINQ-to-SQL updates a record in the database, it needs to know exactly what fields were changed in order to only update those. You basically have three options:
When the updated data is posted back to the web server, load the existing data from the database, assign all properties to the loaded object and call SubmitChanges(). Any properties that are assigned the existing value will not be updated.
Keep track of the unmodified state of the object and use Attach with both the unmodified and modified values.
Initialize a new object with all state required by the optimistic concurrency check (if enabled, which it is by default). Then attach the object and finally update any changed properties after the attach to make the DataContext change tracker be aware of those updated.
I usually use the first option as it is easiest. There is a performance penalty with two DB calls but unless you're doing lots of updates it won't matter.

Adding table from another database to ASP.NET Dynamic Data + Entity Framework

I have a table in another database I would like to scaffold via ASP.NET Dynamic Data and incorporate into my existing Entity Model - is there anyway to do this? (eg using a view or other mechanism or customize the view, edit or insert operations via ad-hoc SQL or stored procedures?)
I don't want to replicate the entire DynamicData sub-folder structure and create another entity model for just one table
I was able to solve this by manually creating an entity in the SSDL and CSDL sections of the .edmx file by using a DefiningQuery and then defining the EntitySets for my entity class
I also added insert / update / delete Function elements to the SSDL with inline SQL using the CommandText property
At this point I had enough to let the Designer map the CRUD methods to these inline SQL functions I defined
It's a little tricky but it works and the general approach opens up many possibilities I had not thought about

How do I define a database view using Entity Framework 4 Code-First?

How do I define a database view using Entity Framework 4 Code-First? I can't find anything about this anywhere!
That's because you cannot define database view using code-first approach. Database view is database construct which uses SQL Query on top of existing tables / functions. You can't define such constructs using code first.
If you want view you must create it manually by executing CREATE VIEW SQL script for example in custom initializer - it will be similar like this answer. Just be aware that this will not help you if you want to map entity to a view. In such case you would probably have to first drop table created by EF and create view with the same name (I didn't try it but it could do the trick). Also be aware that not every view is udpatable so you will most probably get read only entity.
To do a view you create the model, then in the initializer you run the SQL statement to create the view directly against the context with the first line of code, and then in the context you override OnModelCreating and run the second line of code to ignore the model.
context.Database.ExecuteSqlCommand(Resources.<resourcename>);
modelBuilder.Ignore<modeltype>();

How to update entity objects without deleting?

I have an entity generated from my database that contains one table. When i make changes in the DB i obviously would like these changes to reflected in my model.
My current approach is to delete the item from the designer and then right-click - update model from database. This works for me at the moment. Is there a different approach to refreshing these entity tables ?
Why are you deleting them? You can simply right click on your model and select Update Model From Database... and you are done.

Linq update problem

I have an application with user and admin sections. If an admin updates data with the help of sql datasource then it's updated the database. However, when we retrieve data with linq query then it's showing its old value rather than the updated value.
After some time, the linq query automatically shows the correct value.
I think its caching the value, but I find myself helpless. Please help me with this.
When you say
when we retrieve data with linq query
Do you mean you call your select methods again or are you using the current in memory objects?
In either case, you can always refresh an entity with :
Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, entity)
Make sure that you're using your DataContext efficiently (ideally one per unit of work).
After each update, make sure you call DataContext.SubmitChanges(); to commit your changes back to the database.
Also be aware that any context you instanciate between your changes being added to another context and calling SubmitChanges() will not reflect those changes.

Resources