EF Code First - 1-to-1 Optional Relationship

前端 未结 1 1516
温柔的废话
温柔的废话 2020-11-28 06:46

I want to map an optional 1-to-1 relationship in an existing database with EF Code First.

Simple schema:

User
 Username
 ContactID

Contact
 ID
 Name         


        
相关标签:
1条回答
  • 2020-11-28 07:21

    One solution would be;

    public class User
    {
        [Key]
        public string Username { get; set; }
    
        public virtual Contact Contact { get; set; }
    }
    
    public class Contact
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
    
        public virtual User User { get; set; }
    }
    
            modelBuilder.Entity<User>()
                .HasOptional<Contact>(u => u.Contact)
                .WithOptionalDependent(c => c.User).Map(p => p.MapKey("ContactID"));
    

    You set only your navigational objects in your POCOs and instead you use fluent API to map your key to the correct column.

    0 讨论(0)
提交回复
热议问题