Get changes to entity after update in database - entity-framework

I do this to save new invoince in my Invoices database table:
// insert invoice into EDM
edmx.AddToInvoices(newinvoice);
// save EDM changes to datastore
edmx.SaveChanges();
I have a trigger on one of the columns that gets computed dynamically by the database. What is the 1) easiest way to get that value out of the database immediatelly after it changes, 2) What is the fastest way?
Thanks

You can either call Refresh:
MyEntities.Refresh(RefreshMode.StoreWins, someEntity);
...or configure the column in SSDL as store-generated if you never set it on the client.

Since the Entity Framework can't know anything about the trigger, you'd have to reload the entity with a new query.
I strongly recommend finding a different solution, if possible. Triggers can be evil.

Related

Entity Framework ValueGeneratedOnAdd with no requery

Say I have EntityFramework Core 2.1.14.
Say I have to integrate data into a legacy MySql database which was created by a self-taught.
Say also that one of the tables in this database has a surrogate key field that is generated on Add.
Say then that I want to use context.SaveChanges() to handle the Insert DML generation for me because I want to be lazy and because these tables are messy.
Say finally that I do not want Entity Framework to perform a follow-up query to retrieve this surrogate field; I don't care what it is. I just need it generated on insert.
How would one call context.SaveChanges() with an Added object having a property configured as .ValueGeneratedOnAdd() but also instruct Entity Framework to do nothing but generate my INSERT ? I don't want it to return the id.

If I use EF Code First then how can I add another column to a table?

I created POCO classes and then EF created the database tables for me when I tried to access the data. This worked without problem. I have now populated my tables with data. Not just seed data but real data.
Now I would like to add another column to a table. I assume the first thing I need to do is to add a field to the POCO class but what's next after that? I now have my database filled with data. On the SQL side I know how to add the column myself but do I have to do something with EF or will it automatically pick up that my column was added to the table and my field to the POCO class?
You can use Code First Migrations (http://msdn.microsoft.com/en-us/library/hh770484(v=vs.103).aspx). It can update your database automatically or not.

EF CodeFirst: Rails-style created and modified columns

Using Entity Framework CodeFirst, how do I create a created datetime column that gets populated with the current timestamp everytime a record is inserted for that table, and a modified datetime column that has a timestamp generated evertime a row is updated? Rails does this by default and I was hoping the EF generated database would have this as well, but it doesn't. Is this something that can be done with data annotations? If so, how?
Thanks!
It is not supported in EF. EF will not create these columns for you automatically. You must do it yourselves by either:
Have Created and Modified properties in every entity where you want to maintain these values. You must also manually maintain these columns in your application (common approach is overriding SaveChanges and set values accordingly).
If you don't need these values mapped (you never expect to use them in your application and you are happy with the logic in the database) you can create custom database initializer which would execute your custom SQL to alter tables and add those columns, default constraints for Created columns and update triggers for Modified columns.

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 SET IDENTITY_INSERT

Is there a way to force the ID value for a new entity in EF when we have an auto-incrementing ID column, i.e. use SET IDENTITY_INSERT behaviour through EF?
Our requirement is that our create form must always show a new, unique ID for the object we're creating on the empty form before it is filled in or saved. The idea is that this ID can be out read to someone over the phone and then the user can complete and save the form after the call is complete. We could reserve an ID by inserting an empty row into the database there and then, but we have unique columns and FKs; instead I've made a 'next ID' table that we increment with locks for safety, and I test this against the top ID in the object table too to be careful. The idea was to then force the use of this new ID when we write back the entity - but I can't see how to get EF to do it.
Is that possible - is it just something I've missed? I don't think the ID even makes it down to the insert so I don't think manually calling SET IDENTITY_INSERT around the SaveChanges would help.
Or do I have to do something else? I can see alternatives:
Change our ID column to not be an identity and take manual control of it all: there's a table ID inheritance here so this is potentially tricky too.
Separate DB ID and user-visible ID into a separate column, and record our unique ID there.
Empty row to reserve the ID, as above; might need some nullability changes, and amending our data read code to ignore these records.
Thanks! This is EF4 (using an EDMX and generated classes not POCOs), and against SQL Server 2008 in case that matters.
Why not use a Guid as primary key. Nothing to do with auto-increment, no concurrency pitfalls etc. You just create the Guid at the moment you create the form. Hand it over to a caller and fill in the form afterwards. When the form is cancelled, no problem. When the form is finished create the entity with the created Guid set the other values of the entity object, apply it to the (a) context and SaveChanges()...
Alternatives that wont alter your schema
Use EF Transaction
You can call context.SaveChanges() and get the autoincremented primary key. Once the process is completed you can commit the transaction. If the transaction is cancelled or there is an error/exception, you can always rollback so you wont have holes/dirty-data in your rows. I suggest you use the singleton pattern and pass the same transaction/context to whatever methods or screens to complete the process.
Just add an additional status: Draft
Save empty form as draft with saved ID, then proceed to edit the form with the information. Once complete save the form as final/ready. If you wont proceed to save the form, you can always recycle the draft.