I want to make a many to many relationship in a code first Database using Entity Framework ASP.Net and it will be from the same table.
I have users and I want to make every user has his own friends (users too) but i can't establish such a relation in the code first database.
Here is my class.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
namespace LMS.Model.Entites
{
public class user
{
[Key]
public int ID { get; set; }
[Required(ErrorMessage ="Please Insert your name")]
public string Name { get; set; }
[Required(ErrorMessage ="Please insert a valid username")]
public string User_Name { get; set; }
public string Adress { get; set; }
[DataType(DataType.Date)]
public string Birthday { get; set; }
[Required]
[EmailAddress]
public string E_Mail { get; set; }
[Required(ErrorMessage = "Please insert a valid password")]
[MinLength(9)]
[DataType(DataType.Password)]
public string Password { get; set; }
public string Authority { get; set; }
public virtual ICollection<user_Friends> friends { get; set; }
}
}
I tried to make a new class as a new table to make that many to many relation but it failed.
using LMS.Model.Entites;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LMS.Model
{
public class user_Friends
{
[Key]
public virtual user USER1 { get; set; }
[ForeignKey("USER1")]
public virtual int USER1_ID { get; set; }
[Key]
public user USER2 { get; set; }
[ForeignKey("USER2")]
public int USER2_ID { get; set; }
}
}