Jacob Sobus
Jacob Sobus

Reputation: 981

Deleting/adding self referring "friend" using Entity Framework 4.1 - DB First approach

I got User model generated by ET 4.1 - I made DB first:

public partial class User
{
    public User()
    {
        this.Photos = new HashSet<Photo>();
        this.Posts = new HashSet<Post>();
        this.My_requests = new HashSet<User>();
        this.Requests = new HashSet<User>();
        this.FriendLeft = new HashSet<User>();
        this.FriendRight = new HashSet<User>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public string Project { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
    public string House_number { get; set; }
    public string Apartment_number { get; set; }
    public string username { get; set; }
    public string Zip_code { get; set; }

    public virtual ICollection<Photo> Photos { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
    public virtual ICollection<User> My_requests { get; set; }
    public virtual ICollection<User> Requests { get; set; }
    public virtual ICollection<User> FriendLeft { get; set; }
    public virtual ICollection<User> FriendRight { get; set; }
}

Every 'User' can invite other 'User' to become his friend. So when someone invite you, he appear in 'Request', when you invite someone he appear in 'My_requests'. That data is strored in 'Friend_requests' table wchich look like:

ProposerId(col1) RecipientId(col2)

and both columns are in relationship with User table by UserId - it's many to many.

My problem is to delete row from 'Friend_request', because EF doesn't give me context for that table, instead it generated model shown before...

I tried something like that:

User User2 = GetUserInfo(UserId2);
context.Users.Where(u => u.Id.Equals(UserId1)).SingleOrDefault().Requests.Remove(User2);
context.SaveChanges();

But thats of course wrong, it gave me an error:

"Can't update EntitySet „Friends_Request”, because it has element DefiningQuery, and in element there is no element , wchich can handle this operation."

And my questions are:
How I can delete and how to add rows to table 'Friend_Requests'?

EDIT:

Table relations:
enter image description here

And in model generated by ET it's:
My_requests -> when User is Proposer
Requests -> when User is Recipient

Still the problem is how to add new "Friend requests" and how to delete them?

Upvotes: 4

Views: 610

Answers (1)

Jacob Sobus
Jacob Sobus

Reputation: 981

Of course Slauma as a experienced EF user, was right from the beginning. Without keys on Friends table it won't work. Add/remove elements now works normally as i write before. Just use like normal List. Learn on your own mistakes :)

Upvotes: 0

Related Questions