我的MVC模型(国家,州和城市)有三个课程,如下所示
public class Country
{
public int CountryID { get; set; }
public string Name { get; set; }
}
public class State
{
public int StateID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public virtual Country Country { get; set; }
}
public class City
{
public int CityID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public State State { get; set; }
public City()
{
State = new State();
}
}
在向数据库添加新国家时,我没有任何问题,因为它没有任何外键引用,但是当我添加新状态或城市时,它显示验证错误,因为某些字段为空。因此,在插入新状态时,我将状态对象中的国家/地区对象属性初始化为其各自的国家/地区对象,但在此我遇到的问题是,当我插入新状态时,其已经位于数据库中的相应国家/地区是再次添加到国家/地区表中,从而在国家/地区表中生成同一国家/地区的两个副本。和城市和州相同的问题。有人可以帮助我......
感谢提前