Entity framework code-primera clave foránea nula


Tengo un User Country modelo. Un usuario pertenece a un país, pero no puede pertenecer a ninguno (clave foránea nula).

¿Cómo puedo configurar esto? Cuando intento insertar un usuario con un país nulo, me dice que no puede ser nulo.

El modelo es el siguiente:

 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

Debe hacer que su clave foránea sea 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-14 19:49:32

Ahora tengo el mismo problema , Tengo clave externa y necesito ponerla como nullable, para resolver este problema debe poner

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

En la clase DbContext Lo siento por responder muy tarde :)

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-24 15:21:11

Prefiero esto (abajo):

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

Porque EF estaba creando 2 claves foráneas en la tabla de la base de datos: CountryID, y CountryId1, pero el código about lo arregló.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-17 10:10:36