Entities in 'Y' participate in the 'FK_Y_X' relationship. 0 related 'X' were found. 1 'X' is expected

c# entity-framework-6 generics

Question

I have a 1..* relationship between X and Y, where X is the parent. When I try and delete record Y I get the following exception message:

Entities in 'Y' participate in the 'FK_Y_X' relationship. 0 related 'X' were found. 1 'X' is expected.

I am currently trying to delete the record in a generic, disconnected manner in the following way:

public bool Delete(TEntity entity)
{
    if (entity == null)
    {
        return false;
    }
    try
    {
        var entry = _context.Entry(entity);
        entry.State = EntityState.Deleted;
        _context.SaveChanges();
        return true;
    }
    catch
    {
        return false;
    }
}

The entity that is passed in is loaded with AsNoTracking() on the same context.

Any ideas?

1
12
7/14/2014 9:46:13 AM

Popular Answer

Try to add a public property YId to X which will hold the connection to Y, this solved my issue, i use Breeze with EF6 and i've got the same error.

Class Y 
{
    public int Id { get; set; }
    public ICollection<X> Xs { get; set; }
}

Class X 
{
    public int Id { get; set; }
    public int YId { get; set; }   
    public Y Y { get; set; }
}
5
12/21/2014 5:13:53 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow