Sha*_*ean 98 mapping entity-framework foreign-key-relationship ef-code-first entity-framework-4.1
我有一个User
< Country
模特.用户属于某个国家/地区,但可能不属于任何(空外键).
我该如何设置?当我尝试插入具有空国家/地区的用户时,它告诉我它不能为空.
模型如下:
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;}
}
Run Code Online (Sandbox Code Playgroud)
错误: A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}
Lad*_*nka 147
您必须使您的外键可以为空:
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
public virtual Country Country { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
小智 9
我现在有同样的问题,我有外键,我需要把它设为可空,要解决这个问题,你应该把
modelBuilder.Entity<Country>()
.HasMany(c => c.Users)
.WithOptional(c => c.Country)
.HasForeignKey(c => c.CountryId)
.WillCascadeOnDelete(false);
Run Code Online (Sandbox Code Playgroud)
在 DBContext 课上,我很抱歉很晚才回答你:)
我喜欢这个(下):
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
[ForeignKey("CountryId")]
public virtual Country Country { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
因为EF在数据库表中创建了2个外键:CountryId和CountryId1,但是上面的代码解决了这个问题。
归档时间: |
|
查看次数: |
80369 次 |
最近记录: |