If you need a 1-n relation from User to Contact you need an additional navigation property. To be sure about EF behaviour you can also configure the model.
This is an example.
[Table("User78")]
public class User
{
[Key]
public int Id { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
public virtual User MyPreferredUser { get; set; }
}
[Table("Contact78")]
public class Contact
{
[Key]
public int Id { get; set; }
public virtual User User { get; set; }
}
public class Context : DbContext
{
public Context()
{ }
This is the context configuration
public Context(DbConnection connection)
: base(connection, true)
{ }
public DbSet<User> Users { get; set; }
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(_ => _.Contacts)
.WithOptional(_ => _.User)
.Map(_ => _.MapKey("UserId"));
modelBuilder.Entity<User>()
.HasOptional(_ => _.MyPreferredUser)
.WithMany()
.Map(_ => _.MapKey("ContactId"));
}
}
in this example you cannot navigate from contact to user using the MyPreferredUser relation. If you need so you need to add a new navigation from contact to user (of type ICollection).
This is the DML generated by EF during migration
ExecuteNonQuery==========
CREATE TABLE [Contact78] (
[Id] int not null identity(1,1)
, [UserId] int null
);
ALTER TABLE [Contact78] ADD CONSTRAINT [PK_Contact78_a31c6496] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [User78] (
[Id] int not null identity(1,1)
, [ContactId] int null
);
ALTER TABLE [User78] ADD CONSTRAINT [PK_User78_a31c6496] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE INDEX [IX_UserId] ON [Contact78] ([UserId])
ExecuteNonQuery==========
CREATE INDEX [IX_ContactId] ON [User78] ([ContactId])
ExecuteNonQuery==========
ALTER TABLE [Contact78] ADD CONSTRAINT [FK_Contact78_User78_UserId] FOREIGN KEY ([UserId]) REFERENCES [User78] ([Id])
ExecuteNonQuery==========
ALTER TABLE [User78] ADD CONSTRAINT [FK_User78_User78_ContactId] FOREIGN KEY ([ContactId]) REFERENCES [User78] ([Id])
public Guid? ContactId {get;set;}and[ForeignKey("ContactId")]. You want to 1-n relation forUsertoContactsoContactshould be defined as collection; i.e.public virtual ICollection<Contact> Contacts {get; set;}