Kirsten
Kirsten

Reputation: 18160

Why does DbContext FirstOrDefault ignore entities that have been added?

I want to search an entityset for objects that I have added to it - but it cant find the object

When I call this proc multiple times with the same entitytypename it always adds a new object. Why?

private EntityRegister  GetEntityRegister(string entityTypeName)
    {
        var er = Db.EntityRegisters.FirstOrDefault(e => e.Name == entityTypeName);
        if (er == null)
        {
            er = new EntityRegister()

            {
                Name = entityTypeName 

            };
            Db.EntityRegisters.Add(er);


        }
        return er;
    }

Upvotes: 0

Views: 974

Answers (1)

Pawel
Pawel

Reputation: 31610

Did you save changes? FirstOrDefault goes to the database if you did not save changes the newly added entity is not in the database and therefore FirstOrDefault returns null.

Upvotes: 2

Related Questions