Entity Framework code-pierwszy null klucz obcy

Mam User Country model. Użytkownik należy do kraju, ale nie może należeć do żadnego (null foreign key).

Jak to skonfigurować? Kiedy próbuję wstawić użytkownika z null country, mówi mi, że nie może być null.

Model jest następujący:

 public class User{
    public int CountryId { get; set; }
    public Country Country { get; set; }
}

public class Country{
    public List<User> Users {get; set;}
    public int CountryId {get; set;}
}

Error: A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}

Author: Shawn Mclean, 2011-04-14

3 answers

Musisz uczynić swój klucz obcy nullable:

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    public virtual Country Country { get; set; }
}
 127
Author: Ladislav Mrnka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-14 19:49:32

Mam teraz ten sam problem , Mam klucz obcy i muszę go umieścić jako nullable, aby rozwiązać ten problem należy umieścić

    modelBuilder.Entity<Country>()
        .HasMany(c => c.Users)
        .WithOptional(c => c.Country)
        .HasForeignKey(c => c.CountryId)
        .WillCascadeOnDelete(false);

W klasie DBContext Przepraszam za późną odpowiedź:)

 0
Author: Yaman Melhem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-24 15:21:11

Wolę to (poniżej):

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

Ponieważ EF tworzył 2 klucze obce w tabeli bazy danych: CountryId i CountryId1, ale Kod o tym naprawił.

 0
Author: user1040323,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-17 10:10:36