Trending September 2023 # Entity Framework Delete By Id # Suggested October 2023 # Top 12 Popular | Speedmintonvn.com

Trending September 2023 # Entity Framework Delete By Id # Suggested October 2023 # Top 12 Popular

You are reading the article Entity Framework Delete By Id updated in September 2023 on the website Speedmintonvn.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested October 2023 Entity Framework Delete By Id

Introduction to Entity Framework Delete by ID

Entity Framework Delete by ID is used to delete the record based on the ID; we can make use of the Remove or RemoveRange method to spot it as Delete. In the disconnected scenario, we can attach it to the context and mark it as Delete state. By calling the SaveChanges it will post the delete query to the database.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Overview of Entity Framework Delete by Id

The Entity Framework creates and run the Delete Statement in the database for the entities EntityState is marked as Deleted.  To deleting the entity DbContextRemove() method is used. Let’s see the following example which deletes the Department based on the ID as follows,

var deptObj = new Department()

{

Id = 1005

};

using (var dbContext = new CampusDB())

{

dbContext.Remove(deptObj);

await dbContext.SaveChangesAsync();

}

The Entity Framework spots the 3rd ID’s EntityState as Deleted, once the method Remove() is called for department entity. So the while calling the SaveChangesAsync() method the 3rd record of department is deleted from the database.

How to Delete by Id with Entity Framework?

To delete the record, if an entity has a relationship with other entities like One-to-Many or One-to-One then delete the associated data, the relationship is configured once the root entity is deleted. To define the Referential Constraint Options by using the Fluent API of Entity Framework Core, there are of 4 types they are,

ClientSetNull – there Foreign Key (FK) properties will be set to Null. ClientSetNull is the default value.

Cascade – in this the related entities are also deleted.

Restrict – this prevents the cascade delete

SetNull– the Foreign Key (FK) properties will be set to Null.

In the application open the Database Context File and set the Referential Constrains with OnDelete() method. In the method OnDelete() set the DeleteBehavior to Cascade. Look at the code below as follows,

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

.IsRequired()

.HasMaxLength(25)

.IsUnicode(false);

.IsRequired()

.HasMaxLength(100)

.IsUnicode(false);

.OnDelete(DeleteBehavior.Cascade)

.HasConstraintName(“FK_EmployeeMaster_DepartmentMaster”);

});

}

As of now while deleting the record in the DepartmentMaster table the associated records in EmployeeMaster table also deleted automatically. To look at the following code here we deleting the 7th ID of Department, so that the entire employees which are in 7th department also get deleted automatically.

using (var dbcontext = new CampusDB())

{

dbcontext.Remove(deptObj);

await dbcontext.SaveChangesAsync();

}

Entity Framework Delete Records

In Entity Framework for deleting the records, we need to analyze how to delete the entity depends on the record which is in Connected Scenario or Disconnected Scenario. For the Connected Scenario we required to make use of the Remove or RemoveRange method to spot the record as Deleted, whereas in Disconnected Scenario we can connect it to the context and place the state as Deleted.  By calling the SaveChanges it will transmit the delete query to the database. Let’s see the two scenarios as follows,

Connected Scenario – in Connected Scenario the deleting process is straight forward, to query the department entity from the database. To make a call to the Remove () method and send the Department object to the delete state. In EF the Change Tracking marks the entity as Deleted. At last the SaveChanges () method removes the Department from the database by using the Delete Query.

Department deptObj;

//deleting in  Connected Scenario

using (CampusContext dbContext = new CampusContext())

{

dbContext.Database.Log = Console.WriteLine;

dbContext.Department.Remove(deptObj);

dbContext.SaveChanges();

Console.WriteLine(“The Department {0} ({1}) is Deleted “, deptObj.deptObjt_Name, deptObj.Department);

Console.ReadKey();

}

In SQL Query we deleting by using the following statement,

DELETE [dbo].[Departments] WHERE ([Dept_ID][email protected])

Disconnected Scenario – in disconnected scenario initially we are retrieving the Department Entity and we disconnecting (close) the context and then opening the new context to make use of db.Entry method to spot the Deleted State. In case the Model not presents in the context then the Entry method included to the context and spots the state as Deleted.

Department deptObj;

//deleting in Disconnected Scenario

using (CampusContext  dbContext  = new CampusContext ())

{

dbContext chúng tôi = Console.WriteLine;

}

using (CampusContext  dbContext  = new CampusContext ())

{

dbContext chúng tôi = Console.WriteLine;

dbContext .Entry(deptObj).State = System.Data.Entity.EntityState.Deleted;

dbContext .SaveChanges();

}

Deleting record without loading from the database

To delete the entity without loading from the database, by using the Primary Key. Let see the following example which shows deleting record without loading the database. Let’s create new department entity and give Department ID as 2. And then attach it to the context and spot the Deleted State. The method SaveChanges Entity Framework will delete the department.

public void DeleteDisconnectedWithoutLoading()

{

Department deptObj;

deptObj = new Department() { DepartmentID = 2 };

using (CampusContext db = new CampusContext())

{

db.Database.Log = Console.WriteLine;

db.Entry(deptObj).State = System.Data.Entity.EntityState.Deleted;

db.SaveChanges();

}

Console.WriteLine(“Here the Department {0} is Deleted “, deptObj.DepartmentID);

Console.ReadKey();

}

Delete the Records in multiples

To delete the multiple record uses the RemoveRange method of DbSet this removes several records at a time. Let’s see the following example which deletes the department id 3 from the database in the connected scenario, the Entity Framework transmits only one delete query at time to the database so that we need to delete 100 records the EF will issue 100 delete statements,

public void DeleteMultipleRecordsConnected()

{

//to delete the multiple records

using (CampusContext dbContext = new CampusContext())

{

dbContext.Database.Log = Console.WriteLine;

dbContext.Departments.RemoveRange(deps);

try

dbContext.SaveChanges();

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

}

Console.ReadKey();

}

Look at the following code for deleting the multiple records in disconnected scenario,

public void DeleteMultipleRecords_Disconnected()

{

deptObj.Add(new Department { dept_ID = 1 });

deptObj.Add(new Department { dept_ID = 2 });

//to delete multiple records in disconnected scenario

using (CampusContext dbContext = new CampusContext())

{

dbContext.Database.Log = Console.WriteLine;

dbContext.Entry(deptObj).State= System.Data.Entity.EntityState.Deleted;

try

{

dbContext.SaveChanges();

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

}

Console.ReadKey();

}

Conclusion

In this article we have learned about how to deleting the record based on ID in Entity Framework, EF deleting by ID is applied through the Remove or RemoveRange method to spot as Delete. Hope the article helps you to understand with programmatically.

Recommended Articles

This has been a guide to Entity Framework Delete by ID. Here we discussed the Introduction, How to Delete by Id with Entity Framework? examples with code implementation. You can also go through our other suggested articles to learn more –

You're reading Entity Framework Delete By Id

Update the detailed information about Entity Framework Delete By Id on the Speedmintonvn.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!