EF Code First - 1-to-1 Optional Relationship

£可爱£侵袭症+ 提交于 2019-11-26 08:08:49

问题


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

Obviously ContactID joins to Contact.ID. The ContactID field is nullable so the relationship is optional - 0 or 1, never many.

So how do I specify this relationship in EF Code First, with this existing schema?

Here\'s what I\'ve tried so far:

public class User
{
    [Key]
    public string Username { get; set; }
    public int? ContactID { get; set; }

    [ForeignKey(\"ContactID\")]
    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);

I get the following Exception:

  System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role
 \'User_Contact_Source\' in relationship \'User_Contact\'. Because the Dependent 
Role properties are not the key properties, the upper bound of the multiplicity 
of the Dependent Role must be *.

回答1:


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.



来源:https://stackoverflow.com/questions/6021135/ef-code-first-1-to-1-optional-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!