我正在尝试使用一对多的关系将数据插入到数据库中:
我有两种模式:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public virtual Country Country { get; set; }
}
public class Country
{
public int Id { get; set; }
public string CountryName { get; set; }
public virtual ICollection<User> Users { get; set; }
}
User user = new User()
{
Name = model.Name,
Surname = model.Surname,
Country = new Country { Id = 1 }
};
当我尝试将其插入数据库时,我得到异常
一个或多个实体的验证失败。
CountryName
字段是必需的(数据库中需要CoutryName
列)
我不希望每次调用数据库来获取完整的Country对象,有什么想法吗?
答案 0 :(得分:3)
不要实例化新国家,而是做这样的事情:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int CountryId { get; set; }
[ForeignKey("CountryId")]
public virtual Country Country { get; set; }
}
public class Country
{
public int Id { get; set; }
public string CountryName { get; set; }
public virtual ICollection<User> Users { get; set; }
}
User user = new User()
{
Name = model.Name,
Surname = model.Surname,
CountryId = 1;
};
这明确设置用户的CountryID。
答案 1 :(得分:0)
您应该使用“FK Associations”而不是“Independent Associations”这是创建关于它的文章: http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx