0
我似乎无法能够更新与外键约束收到此错误示范:发生了参照完整性约束违规。当更新EF
Additional information: A referential integrity constraint violation occurred: The property value(s) of 'Country.Id' on one end of a relationship do not match the property value(s) of 'Setting.CountryId' on the other end.
设置模式
namespace Domain
{
public class Setting : BaseModel
{
public string Address { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Website { get; set; }
public string Slogan { get; set; }
public byte[] Logo { get; set; }
public string City { get; set; }
public string RegistrationNo { get; set; }
[ForeignKey("State")]
public int StateId { get; set; }
public State State { get; set; }
[ForeignKey("Country")]
public int CountryId { get; set; }
public Country Country { get; set; }
public string IsDefault { get; set; }
}
}
国家示范
namespace Domain
{
public class State :BaseModel
{
public string Name { get; set; }
}
}
国家模型
namespace Domain
{
public class Country : BaseModel
{
public string Name { get; set; }
}
}
库获取和更新设置
public Setting GetSetting()
{
try
{
return _db.Settings.Include("Country").Include("State").First();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public Setting UpdateSetting(Setting setting)
{
try
{
_db.Settings.Attach(setting);
_db.Entry(setting).State = EntityState.Modified;
_db.SaveChanges();
return setting;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
注意我使用WCF代理
按钮单击事件
private void btnSave_Click(object sender, EventArgs e)
{
//MessageBox.Show(Convert.ToInt16(cmbState.EditValue).ToString());
//return;
if (dxValidationProvider1.Validate())
{
if (picLogo.Image == null)
{
XtraMessageBox.Show("Upload Logo");
}
else
{
var setting = proxy.GetSetting();
//MessageBox.Show(cmbState.EditValue.ToString()); return;
setting.HotelName = txtHotelName.Text;
setting.Address = txtAddress.Text;
setting.Email = txtEmail.Text;
setting.Phone = txtPhone.Text;
setting.Website = txtWebsite.Text;
setting.Slogan = txtSlogan.Text;
setting.City = txtCity.Text;
setting.CountryId = Convert.ToInt16(cmbCounty.EditValue);
setting.StateId = Convert.ToInt16(cmbState.EditValue));
setting.Logo = picLogo.Image.ToByteArray();
var s = proxy.UpdateSetting(setting);
MessageBox.Show(@"Updated");
}
}
else
{
MessageBox.Show("Please fill the required fields");
}
}
'CountryId'是'Int32',但你转换'cmbCountry.EditValue'到'Int16',并试图将其分配到'CountryId'。他们是不同的类型。 –
我试过得到相同的错误 – rilly009
我假设'BaseModel'中的属性'Id'是'int'或'Int32'? –