Search code examples
c#entity-framework-4

Remove Items in Entity Collection


How to remove items in Entity Collection?

ex:

I have two entities that is related to each other

Employee and Reference

**Table: Employee**

EmployeeId(PK) 

**Table: Reference**

ReferenceId(PK)
EmployeeId(FK)
Name

first I Initialize this:

Employee empCol = new Employee();
Reference refs = new Reference();

and then I save some data in the Entity Collection

refs.Name = "Sample";
empCol.References.Add(refs);

refs.Name = "Sample2";
empCol.References.Add(refs);

I want to remove the second element in the collection, how can I do that?

[0]= {Name = "Sample"}
[1]= {Name = "Sample2"}

I try this kind of code but it is not working, this code does not removing the second element in my Entity Collection, but it is not producing errors:

empCol.References.ToList().RemoveAt(1);

Solution

  • Dont assume how index is maintained inside by collection. Find the object first, and then remove it from collection

    var ref = empCol.References.FirstOrDefault( r=> r.Name == "Sample");
    if (ref != null)
        empCol.References.Remove(ref);
    

    If you want to remove by index, Find that index first.