我對EF有點新,並嘗試在REST樣式中創建UPDATE方法,該方法將取對象中的一個或多個屬性並更新數據庫,僅傳遞給我。在EntityFramework十進制屬性上設置IsModified
我有下面的代碼工作幾種類型。但是,我最近添加了System.Decimal,並且出現一個錯誤,我無法使用Property()方法,因爲我的小數字段不是Primitive或複雜類型。上下面的行發生了錯誤:
pt.Property(propertyInfo.Name).IsModified = true;
實際的錯誤信息是:
其他資料:類型「預約」屬性「Miles的不是原始的或複雜的特性。 Property方法只能用於原始或複雜屬性。使用參考或收集方法。
我的財產「萬里行」是在SQL和十進制的EF類的18,2十進制以及我的數據模型類。
我花了兩天時間尋找任何線索或解決方案,但毫無進展。幫我歐比旺·克諾比,你是我唯一的希望......
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutAppointment(int id,[FromBody] DTO.Appointment appointment)
{
// Check for invalid model and mis-matched ID
if (!ModelState.IsValid){ return BadRequest(ModelState); }
if (id != appointment.AppointmentID) { return BadRequest(); }
// Create and populate an Appointment Entity which we will use for saving our data later
Appointment tempAppt = new Appointment();
tempAppt.AppointmentID = appointment.AppointmentID;
db.Appointments.Attach(tempAppt);
var pt = db.Entry(tempAppt);
// Loop through all the properties on the object that was passed into this method
// and update the Entity with any that were provided.
foreach (PropertyInfo propertyInfo in appointment.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
switch (propertyInfo.PropertyType.ToString())
{
case "System.Int32":
if ((int)propertyInfo.GetValue(appointment) != -1)
{
pt.Property(propertyInfo.Name).CurrentValue = (int)propertyInfo.GetValue(appointment);
pt.Property(propertyInfo.Name).IsModified = true;
}
break;
case "System.Decimal":
if ((decimal)propertyInfo.GetValue(appointment) != -1)
{
propertyInfo.SetValue(appointment, (decimal)propertyInfo.GetValue(appointment));
pt.Property(propertyInfo.Name).IsModified = true;
}
break;
case "System.String":
if ((string)propertyInfo.GetValue(appointment) != "NONE")
{
pt.Property(propertyInfo.Name).CurrentValue = (string)propertyInfo.GetValue(appointment);
pt.Property(propertyInfo.Name).IsModified = true;
}
break;
case "System.DateTime":
if ((DateTime)propertyInfo.GetValue(appointment) != new DateTime(2099, 1, 1))
{
pt.Property(propertyInfo.Name).CurrentValue = (DateTime)propertyInfo.GetValue(appointment);
pt.Property(propertyInfo.Name).IsModified = true;
}
break;
case "System.TimeSpan":
if ((TimeSpan)propertyInfo.GetValue(appointment) != new TimeSpan(0))
{
pt.Property(propertyInfo.Name).CurrentValue = (TimeSpan)propertyInfo.GetValue(appointment);
pt.Property(propertyInfo.Name).IsModified = true;
}
break;
//case "System.Nullable`1[System.Guid]":
case "System.Guid":
if ((Guid)propertyInfo.GetValue(appointment) != new Guid("00000000-0000-0000-0000-000000000000"))
{
pt.Property(propertyInfo.Name).CurrentValue = (Guid)propertyInfo.GetValue(appointment);
pt.Property(propertyInfo.Name).IsModified = true;
}
break;
}
}
}
你應該接受這個作爲你的答案。對我來說確實是同樣的問題。 – MetalPhoenix