I'm trying to create a user with contacts table. I'm not sure if I'm doing it the right way as there is a column added which I didn't declare.
The entities:
public class User
{
public int Id { get; set; }
public bool IsAvailable { get; set; }
public List<Contact> Contacts { get; set; }
}
public class Contact
{
public int UserId { get; set; }
public int ContactUserId { get; set; }
public User User { get; set; }
public User ContactUser { get; set; }
}
The mapping:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>()
.HasKey(x => new { x.UserId, x.ContactUserId });
modelBuilder.Entity<Contact>()
.HasOne(x => x.User)
.WithMany(x => x.Contacts)
.HasForeignKey(x => x.UserId);
modelBuilder.Entity<Contact>()
.HasOne(x => x.ContactUser)
.WithMany(x => x.Contacts)
.HasForeignKey(x => x.ContactUserId);
}
The result:
migrationBuilder.CreateTable(
name: "Contact",
columns: table => new
{
UserId = table.Column<int>(nullable: false),
ContactUserId = table.Column<int>(nullable: false),
UserId1 = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Contact", x => new { x.UserId, x.ContactUserId });
table.ForeignKey(
name: "FK_Contact_User_ContactUserId",
column: x => x.ContactUserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Contact_User_UserId1",
column: x => x.UserId1,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
The real question:
Where is the column UserId1 in contact coming from? Is there something wrong with my definition? Thanks!
Contact
, then n:1 toContact.ContactUser
. So,User
is n:n to itself.User.Contacts
cannot be both the navigation property fromUser
to itsContactUser
s and the navigation property going the other way at he same time. One of those should be configured out from theUser
entity, and the other configured with the parameterlessHasMany()
.