Gaui
Gaui

Reputation: 8959

Entity Framework and one-to-many relationship

I'm trying to set up one-to-many relationship with EF.

A user can have many (or none) access records.

So my set up is the following:

public class User
{
    // ...
    public virtual ICollection<UserAccess> UserAccess { get; set; }
}

public class UserAccess
{
    // ...
    public virtual User User { get; set; }
}

And my code in UserAccessMap:

this.HasMany(t => t.UserAccess).WithMany().Map(m => m.MapLeftKey("USERID"));

What am I doing wrong here?

Upvotes: 0

Views: 161

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

You were doing many to many relationship, see the configuration pattern.

HasMany.. WithMany..

The one to many configuration should be either HasMany.. WithRequired/WithOptional.. or HasRequired/HasOptional.. WithMany...

In UserAccessMap

HasRequired(t => t.User).WithMany(x => x.UserAccess).Map(x=> x.MapKey("USERID"));

Or in UserMap

HasMany(t => t.UserAccess).WithRequired(x => x.User).Map(x=> x.MapKey("USERID"));

Upvotes: 1

Related Questions