考虑以下
MODEL
public partial class ElementType
{
public long ElementTypeId { get; set; }
public LocalizedString TypeName { get; set; }
}
[ComplexType]
public class LocalizedString
{
public string French { get; set; }
public string English { get; set; }
[NotMapped]
public string Current
{
get { return (string) LanguageProperty().GetValue(this,null); }
set { LanguageProperty().SetValue(this, value,null); }
}
public override string ToString()
{
return Current;
}
private PropertyInfo LanguageProperty()
{
string currentLanguage = Thread.CurrentThread.CurrentUICulture.DisplayName;
return GetType().GetProperty(currentLanguage);
}
}
CONTROLLER
public ActionResult ElementType_Read([DataSourceRequest]DataSourceRequest request)
{
List<ElementType> elementTypeList = db.ElementType.ToList();
IQueryable<ElementType> elementTypes = elementTypeList.AsQueryable();
DataSourceResult result = elementTypes.ToDataSourceResult(request, elementType => new
{
ElementTypeId = elementType.ElementTypeId,
TypeName = elementType.TypeName,
});
return Json(result);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ElementType_Destroy([DataSourceRequest]DataSourceRequest request, ElementType elementType)
{
if (ModelState.IsValid)
{
var currentElementType = db.ElementType.Find(elementType.ElementTypeId);
db.ElementType.Attach(currentElementType);
db.ElementType.Remove(currentElementType);
db.SaveChanges();
}
return Json(new[] { elementType }.ToDataSourceResult(request, ModelState));
}
阅读操作按预期工作。我通过TypeName.Current
在Grid视图中获取当前的TypeName但是,如果我尝试执行任何其他操作,例如销毁或更新,我就会遇到此异常 无法转换类型&#39; Iolite.Models.LocalizedString&#39;输入&#39; System.String&#39;。
有任何修复建议吗?
此致
答案 0 :(得分:0)
我建议您使用DTO(数据传输对象)来平滑模型,以便更容易地序列化/反序列化对象。您还将减少将在服务器和服务器之间传输的数据量。每个请求中的客户。
对于您的特定实现,您可以定义DTO如下:
public class ElementTypeDTO
{
public long ElementTypeId { get; set; }
public string TypeName { get; set; }
}
根据这种架构模式,您必须按照以下步骤更改您的操作:
public ActionResult ElementType_Read([DataSourceRequest]DataSourceRequest request)
{
List<ElementType> elementTypeList = db.ElementType.ToList();
IQueryable<ElementType> elementTypes = elementTypeList.AsQueryable();
DataSourceResult result = elementTypes.ToDataSourceResult(request, elementType => new ElementTypeDTO
{
ElementTypeId = elementType.ElementTypeId,
TypeName = elementType.TypeName.Current,
});
return Json(result);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ElementType_Destroy([DataSourceRequest]DataSourceRequest request, ElementTypeDTO elementType)
{
if (ModelState.IsValid)
{
var currentElementType = db.ElementType.Find(elementType.ElementTypeId);
db.ElementType.Attach(currentElementType);
db.ElementType.Remove(currentElementType);
db.SaveChanges();
}
return Json(new[] { elementType }.ToDataSourceResult(request, ModelState));
}