Here’s My Code:
public class RegisteredUser
{
public virtual int ID { get; set; }
[Required]
public virtual string FirstName { get; set; }
[Required]
public virtual string LastName { get; set; }
[Required]
public virtual string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public virtual string Password { get; set; }
public virtual string NickName { get; set; }
[Required]
[DataType(DataType.Date)]
public virtual DateTime DOB { get; set; }
public virtual string Avatar { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<CommentPost> CommentPosts { get; set; }
public virtual ICollection<TagPost> TagPosts { get; set; }
public virtual ICollection<RegisteredUser> Friends { get; set; }
}
public class SocialWeb_BasedApplicationDB : DbContext
{
public DbSet<RegisteredUser> RegisteredUsers { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<CommentPost> CommentPosts { get; set; }
public DbSet<TagPost> TagPosts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>().HasMany(m => m.CommentPost).WithRequired(a => a.Post).WillCascadeOnDelete(false);
modelBuilder.Entity<RegisteredUser>().HasMany(m => m.TagPosts).WithRequired(a => a.RegisteredUser).WillCascadeOnDelete(false);
modelBuilder.Entity<RegisteredUser>().HasMany(a => a.Friends).WithMany().Map(a => a.MapLeftKey("UserID").MapRightKey("FriendID").ToTable("Users_Friends"));
}
The Many To May table is created but i can’t actually use it like i can’t do (from n in Context.User_Friends where n.UserId = 0 select n);
what should i do?
From EF’s perspective, User_Friends is not an entity instead to get the friends of a User you have to use this query
I usually make relationships into explicit entities because there is more information that is useful about these relationships that can’t be captured otherwise.