Entity Framework 4.1 Insert, Update Delete ASP.NET MVC3 - entity-framework

I have a wizard where I am in updatemode. During this mode, I can actually insert, delete or update various records in the model. I am passing by reference to m CRUD methods. eg. MyMethod(ref Project project)
I was able to update by attaching my project to the context but when I also need to Delete during the same tranaction, update and delete do not do anything, How am I supposed to handle delete?
I do the following which does not work.
var FoundProjectUser = (from m in UserRoles where m.UserProfileId == member.UserProfileId select m);
if (FoundProjectUser.Count() == 0)
{
project.ProjectTeams.Remove(member);
}
ANSWER FOUND:
I found the problem. The problem is that in edit mode, the project is not attached to the context. I need to delete from the DBContext and not the project. Like this.Context.ProjectTeams.Remove(member);

.Remove will only flag the row for removal. You have to do entity.SaveChanges() to persist the changes.

Related

Delete link table entry but not referenced table entries

I am using Entity Framework database-first model. I have 2 tables that are referenced by a link table.
For example:
When I update my edmx file from my database this creates the expected model:
Now what I want to do is delete an entry from the Product_User table without deleting the referenced entry in either of the related tables (Product or User).
I've tried both of these statements (together and separately) but neither seems to have any effect:
user.Products.Clear();
foreach (var product in products)
{
product.User = null;
}
Is what I'm trying to do possible with the model the way I have it now? And if so what am I doing wrong?
I noticed I can do what I'm trying to do if I add the link table explicitly to the model but I'm trying to avoid that.
Any help would be much appreciated. Thanks.
Your seconde way to go (with a loop) seems more like the correct way.
Instead of = null try to use the .Remove() function. I guess the remove function only remove the link between the two entity, not the entities related.
See this answer : Removing many to many entity Framework

Entity Framework delete without select and Optimistic Concurrency

I am trying to delete a record if it exists using Entity Framework - I want to generate something like
delete from tbl where id = 1
I don't care whether any records exist, I just want to delete them if they do. I should be able to do with without selecting them first like this:
var record = new tbl { id = 1, rel = new tbl_related { tbl_id = 1 } };
context.tbl.Attach(tbl);
context.tbl.Remove(tbl);
context.SaveChanges();
The syntax might not exactly be there because this isn't a copy and paste, and I've added the foreign key relationship to show that I'm taking this into account.
On running this code the correct SQL is generated by EF and run but I get a System.Data.Entity.Infrastructure.DbUpdateConcurrencyException saying "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded".
However, I'm fully expecting zero rows to be deleted a lot of the time. Any ideas on how I can get around this?
I've been pointed to How to ignore a DbUpdateConcurrencyException when deleting an entity as a possible duplicate. This suggests handling the DbUpdateConcurrencyException which I am now doing (and ignoring), but that post talks about trying to delete rows that might have been deleted - I want to delete rows that might never have existed. I know this might just be a question of semantics because the resolution is the same but I want to highlight that I am doing something that I see as perfectly reasonable and the Framework is not handling it very well.
Thanks
There is an extension for EF on github that allows you to update and delete entities with a single call to the database.
With this extension you can do something like this:
context.tbl.Delete(t => t.Id == 1);
A single call should eliminate your DbUpdateConcurrencyException.

How do i delete single record from table using EF 6.1.1

I am using Entity Framework 6.1.1.
I am deleting single record from table as following but i am not sure whether its the only way or could further rewrite it in an efficient way.
Can someone share comments?
Reason: I am asking because many solutions in earlier posts are referring to EF 4.0 and not using the latest version 6.1.1.
Guid studentId = student.Id;
StudentReportDetail stuDetails = _context.StudentReportDetail.Find(studentId);
if (stuDetails != null)
{
_context.StudentReportDetail.Remove(stuDetails);
_context.SaveChanges();
}
There are no changes about how to delete an entity between EF 4 and EF 6. To delete an entity using Entity Framework, you need to use the Remove method on DbSet. Remove works for both existing and newly added entities.
Calling Remove on an entity that has been added but not yet saved
to the database will cancel the addition of the entity. The entity is
removed from the change tracker and is no longer tracked by the
DbContext.
Calling Remove on an existing entity that is being change-tracked
will register the entity for deletion the next time SaveChanges is
called.
Deleting with loading from the database
As the example you show in your question, you need to load first the existing entity from your context to delete it. If you don't know the Id, you can execute a query as I show below to find it first:
var report= (from d in context.StudentReportDetail
where d.ReportName == "Report"
select d).Single();
context.StudentReportDetail.Remove(report);
context.SaveChanges();
Deleting without loading from the database
If you need to delete an entity, but it’s not already in memory, it’s a little inefficient to retrieve that entity from the database just to delete it. If you know the key of the entity you want to delete, you can attach a stub that represents the entity to be deleted, and then delete this stub. A stub is an instance of an entity that just has the key value assigned. The key value is all that’s required for deleting entities.
var toDelete = new StudentReportDetail {Id = 2 };
context.StudentReportDetail.Attach(toDelete);
context.StudentReportDetail.Remove(toDelete);
context.SaveChanges();
Other way could be changing the entity's state to Deleted.DbContext has methods called Entry and Entry<TEntity>, these methods get a DbEntityEntry for the given entity and provide access to the information about the entity and return a DbEntityEntry object able to perform the action on the entity. Now you can perform the delete operation on the context by just changing the entity state to EntityState.Deleted:
var toDelete = new StudentReportDetail {Id = 2 };
context.Entry(toDelete).State = EntityState.Deleted;
context.SaveChanges();
Using a 3rd party library
There is another way but is using a 3rd party library, EntityFramework Plus, there is a nugget package you can install. You can use the batch delete operation:
context.StudentReportDetail
.Where(u => u.Id== stuDetails)
.Delete();

Rename Navigation Properties while keeping data intact in Entity Framework

Have an Order table with several foreign keys to a User table (different types of users).
The Order entity has multiple properties that represent the keys over to the User table.
The problem is these navigation properties get named User1, User2, User3 etc...
Is there a way to update the names of these properties and keep them intact when updating the datamodel?
For example, some times during development, if I make a change to this table, I will some times delete the table from the model, update and rebuild etc.
I think I will just have to manually rename these properties and remember to do this if I update the table and datamodel, or is there another way?
using db-migration feature helps you to do that. advantage is that it helps you to have an archive of changes you have made during development. for each change you have a class that represent changes happened to database.
after enabling the migration for your project :
first turn off automatic update
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
then use the code-first migration to generate migration class. write this in package manager :
add-migration renameColumns
then edit the created class to replace add/drop with rename.
public override void Up()
{
RenameColumn("Orders", "OldColumn", "NewColumn");
finally run update command in package manager to effect database
Update-Database

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?