Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The entity type 'List<PersonAddress>' was not found. Ensure that the entity type has been added to the model

I'm building an application with .net core 2.0. I have a Person object with a list of addresses. Addresses are stored in the Addresses table. I then have a joining table that relates Person to Addresses.

class Person {
    public List<PersonAddress> Addresses { get; set; } 
}

class Address {
    ...address properties...
}

class PersonAddress{
    public int AddressId { get; set; }
    public Address Address { get; set; }

    public int PersonId { get; set; }
    public Person Person { get; set; }
}

When I save a Person object with a PersonAddress that contains an address, it works great. It inserts a new person, a new address, and a new record in the joining table. (I have configured relationships in the fluent api).

When I try to update, however, I have a problem. After loading a person object with a list of their addresses, I can add, remove, or change the addresses, and the changes are not tracked.

I tried this in my controller to get it to process changes:

dbContext.Entry(person.Addresses).State = EntityState.Modified;

And I get this error:

The entity type 'List<PersonAddress>' was not found. Ensure that the entity type has been added to the model.

It is unquestionably on the model, so I don't know why this isn't working. I trid this:

person.Addresses.ForEach(item => _context.Entry(item).State = EntityState.Modified);

And it was ok with it, but this doesn't track adding or removing, so it's not sufficient.

like image 709
user3413723 Avatar asked Mar 06 '18 19:03

user3413723


1 Answers

My problem was that I had a

var listOfItems = await DbContext.Items.ToListAsync();
DbContext.Remove(listOfItems);

After looking a second (10th) time over it, I realised I needed to change it to:

var listOfItems = await DbContext.Items.ToListAsync();
DbContext.RemoveRange(listOfItems);

So just needed to change from Remove to RemoveRange .

like image 196
Andrei Ivanov Avatar answered Sep 24 '22 21:09

Andrei Ivanov