[Key, Column(Order = 0)] public string ProgrammerId { get; set; } [Key, Column(Order = 1)] public int SkillId { get; set; } public virtual ProgrammerProfile Programmer { get; set; } public virtual Skill Skill { get; set; } public int KnowledgeLevel { get; set; } - And how did you try and what did not work out? - Andrey NOP
1 answer
Suppose you have such an entity:
public class EntityProg { [Key, Column(Order = 0)] public string ProgrammerId { get; set; } [Key, Column(Order = 1)] public int SkillId { get; set; } public int KnowledgeLevel { get; set; } public virtual ProgrammerProfile Programmer { get; set; } public virtual Skill Skill { get; set; } } Suppose you have a DbSet such entities in the context:
public virtual DbSet<EntityProg> EntityProgs { get; set; } Suppose you want to delete one such entity by the two keys programmerId and skillId :
// попытаемся найти сущность по двум ключам var record = context.EntityProgs .SingleOrDefault(_ => _.ProgrammerId == programmerId && _.SkillId == skillId); // если такая сущность найдена, удалим if (record != null) { context.EntityProgs.Remove(record); context.SaveChanges(); } Also, there is a method of removing the collection RemoveRange , with which you can delete several entities at once. It's simple, you first need to find the entity in the context, pull it out and put it into a variable, and then transfer it to the desired DbSet method ( Remove or RemoveRange - depending on whether you need to delete one entity or several).
Alternatively, you can go another way (using the Attach method to not select and send a SELECT before deleting):
var entityProg = new EntityProg { ProgrammerId = programmerId, SkillId = skillId }; context.EntityProgs.Attach(entityProg); context.EntityProgs.Remove(entityProg); context.SaveChanges(); But that's not all, you can go ahead and mark the entity as remote through its state, for example:
var entityProg = new EntityProg { ProgrammerId = programmerId, SkillId = skillId }; context.EntityProgs.Attach(entityProg); context.Entry(entityProg).State = EntityState.Deleted; context.SaveChanges(); Source link: Delete a single record from Entity Framework?
Useful links to explore:
- oneWell, the standard recommendation is to use Attach, so as not to send select before deleting (besides, we have a primary key and the object certainly exists in one copy) - Andrey NOP