简体   繁体   中英

Entity Framework self referencing entity

I have a problem with the Entity Framework.

public class User : Receiver
{
    public User()
    {
        if (Groups == null)
            Groups = new List<Group>();
        if (Buddies == null)
            Buddies = new List<User>();
    }

    [Required]
    public string PhoneNumber { get; set; }
    [ForeignKey("Guid"), JsonIgnore]
    public IList<User> Buddies { get; set; }
    [ForeignKey("Guid"), JsonIgnore]
    public IList<Group> Groups { get; set; }
}

public class Receiver
{
    public Receiver()
    {
        Guid = Guid.NewGuid();
        Created = DateTime.Now;
    }

    [Key]
    public Guid Guid { get; set; }
    [Required]
    public DateTime Created { get; set; }
}

When i try to add a user...

User user = new User
            {
                Guid = new Guid("8cd094c9-e4df-494e-b991-5cf5cc03d6e3"),
                PhoneNumber = "+4991276460"
            };

        cmc.Receivers.Add(user);

... it ends in follogwing error.

The object of the Type "System.Collections.Generic.List`1[Project.Models.User]" can't be converted to "Project.Models.User".

When i comment out following two lines:

[ForeignKey("Guid"), JsonIgnore]
    public IList<User> Buddies { get; set; }

...the programm runs fine.

I hope someone can help me to fix this problem.

Otherwise it runs into an error at this line : cmc.Receivers.Add(user);

In your mapping...

[ForeignKey("Guid"), JsonIgnore]
public IList<User> Buddies { get; set; }

...you specify that User.Buddies is part of a one-to-many relationship and that User.Guid (= Receiver.Guid ) is the foreign key in this relationship. But User.Guid is also the primary key, hence it must be unique. As a result a User cannot have a list of Buddies but only a single reference.

The mapping makes no sense but the exception is not very helpful and difficult to understand. (Somehow EF seems to recognize internally that the Buddies cannot be a list with that mapping and wants to cast the list to a single reference. It should detect in my opinion that the mapping is invalid in the first place.)

For a correct one-to-many mapping you need a foreign key that is different from the primary key. You can achieve that by either removing the [ForeignKey] annotation altogether...

[JsonIgnore]
public IList<User> Buddies { get; set; }

...in which case EF will create a default foreign key in the Receivers table (it will be some column with an underscore in its name, but you can rename that with Fluent API if you don't like the default name) or by adding your own foreign key property to the User class:

public Guid? BuddyGuid { get; set; }

[ForeignKey("BuddyGuid"), JsonIgnore]
public IList<User> Buddies { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM