Combining Entity Framework Foreign Keys from One to Zero or One

I am trying to modify the source code of an existing application to use First Entity Framework Code. I used the built-in tool in Visual Studio 2015 to create POCO classes based on my existing database. This worked fine for the most part, with the exception of two classes, with a one to zero or one relationship. These are my (simplified) classes:

public class Login { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public int TeamMemberId { get; set; } public virtual TeamMember TeamMember { get; set; } } public class TeamMember { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public virtual Login Login { get; set; } } 

With the following configuration:

 public class LoginTypeConfiguration : EntityTypeConfiguration<Login> { public LoginTypeConfiguration() { this.HasRequired(e => e.TeamMember) .WithOptional(e => e.Login); this.Property(e => e.TeamMemberId) .HasColumnName("TeamMember_Id"); } } 

This results in the following migration:

 CreateTable( "dbo.Logins", c => new { Id = c.Int(nullable: false, identity: true), TeamMember_Id = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.TeamMembers", t => t.Id) .Index(t => t.Id); 

For some reason, EF creates a foreign key on [Logins].[Id] instead of [Logins].[TeamMember_Id] . I already tried to decorate my navigation property with the ForeignKey attribute, but that didn't work. Is there any way to get it to create a foreign key on [Logins].[TeamMember_Id] instead?

+2
source share
2 answers

As a result, I created a one-to-many relationship with the [NotMapped] property for login.

My classes:

 public class Login { public int TeamMemberId { get; set; } public virtual TeamMember TeamMember { get; set; } } public class TeamMember { [NotMapped] public virtual Login Login { get { return Logins.FirstOrDefault(); } } public virtual ICollection<Login> Logins { get; set; } } 

With the following configuration:

 public class LoginTypeConfiguration : EntityTypeConfiguration<Login> { public LoginTypeConfiguration() { this.Property(e => e.TeamMemberId) .HasColumnName("TeamMember_Id"); } } 
0
source

To do this, you can write your code first like this. Entity Framework will automatically create a TeamMemberId foreign key for you. For More Information: Entity Framework Tutorial - First Code Terms

 public class Login { public int Id { get; set; } //foreign key declaration public int TeamMemberId { get; set; } public TeamMember TeamMember { get; set; } } public class TeamMember { public int TeamMemberId { get; set; } public Ilist<Login> Login { get; set; } } 
0
source

Source: https://habr.com/ru/post/1268505/


All Articles