Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 312
Stuart Blackler Avatar asked Jul 14 '14 09:07

Stuart Blackler


2 Answers

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; }
}
like image 99
Guy Bertental Avatar answered Oct 15 '22 05:10

Guy Bertental


When you context.Y.Attach(x); make sure that the object x holds the "Id" to the parent entity. You need both.

Example:

x.Id = 3;
x.ParentEntity.Id = 10;

That solved my problem at least. I forgot the parent id in the object which i attached.

like image 33
Jo Smo Avatar answered Oct 15 '22 06:10

Jo Smo