1

I've got a definition like below and essentially, I want to create this in the EmailAccount class:

public EmailUser? EmailUserAccountInfo {get;set;}

the compiler gives me an error about non-nullable types. My goal is I want to make the EmailUser optional. I'm kind of confused because I can set EmailUserAccountInfo = null directly.

var r = new EmailAccount()
                        {
                            EmailUserAccountInfo = null,
                            Id = 1001
                        };



public class EmailAccount
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public EmailUser EmailUserAccountInfo { get; set; }
}


public class EmailUser
{ 
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public EmailAccount EmailAcount { get; set; }

    public string EmailAddress { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string ZipCode { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public int Temperature { get; set; }
    public string WeatherString { get; set; }

    public ImageDetail ImageOfUser { get; set; }
}
Peter Kellner
  • 14,748
  • 25
  • 102
  • 188

1 Answers1

1

You can do this if you add a foreign key and you mark that nullable:

public class EmailAccount
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    // Foreign key    
    public int? EmailUserAccountInfoId { get; set; }

    // Navigation property
    public virtual EmailUser EmailUserAccountInfo { get; set; }
}

See this document about naming conventions for Code-First. (Scroll down to Relationship Convention)

CB-Dan
  • 1,718
  • 2
  • 16
  • 29
  • Thanks Tsuushin, Can you explain what the implication of the virtual keyword is regarding the database? Also, I've had some doubts about whether adding the foreign key column explicitly makes a difference. – Peter Kellner Nov 27 '11 at 18:50
  • Adding the foreign key explicitly allows you to mark it as null-able, thereby instructing EF that the relationship is zero-to-one. – CB-Dan Nov 27 '11 at 23:27
  • As for the virtual keyword, see the [answer to this question](http://stackoverflow.com/questions/5597760/what-effects-can-the-virtual-keyword-have-in-entity-framework-4-1-poco-code-fi) – CB-Dan Nov 27 '11 at 23:29