我似乎无法使用foreignKey约束更新模型以获取此错误:
其他信息:参照完整性约束违规 发生:a。一端的'Country.Id'的属性值 关系与'Setting.CountryId'的属性值不匹配 在另一端。
设置模型
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");
}
}
答案 0 :(得分:0)
我刚从GetSetting函数中删除了Include语句,并更新了所有内容。这解决了我的问题
public Setting GetSetting()
{
try
{
return _db.Settings.First();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}