我已经用OData客户端生成器创建了一个v4客户机。这产生了部分类。我想用IDataErrorInfo.扩展这个生成的类
namespace Client.Model {
public partial class City : IDataErrorInfo
{
public String this[String columnName]
{
return "";
}
public String Error { get { return ""; } }
}
}当我想创建一个新的城市并将它发送到服务器时
ODataContainer container = new ODataContainer(new Uri("http://localhost:45666/odata"));
container.AddToCities(city);我犯了个错误
An exception of type 'Microsoft.OData.Client.DataServiceRequestException' occurred in Microsoft.OData.Client.dll.
The request is invalid. The property "Error" does not exist in Server.Model.City.WebApi配置:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<City>("Cities");
builder.EntitySet<Country>("Countries");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "odata",
model: builder.GetEdmModel());
}
}是否有可能防止请求中包含Error属性?
发布于 2015-07-17 20:40:01
使用OData客户端生成的模型是部分类。当您实现IDataErrorInfo时,它将要求您实现Error属性,这个属性当然不在服务器端。因为您做了一个操作,例如,在实体City上,这个序列化的城市对象,如果有一个错误属性,它也将被序列化。
解决方案可以是,避免这种情况,并将客户端模型与UI分开。你可以试试这个:
namespace Client.Model {
public partial class City
{
public String this[String columnName]
{
return "";
}
}
}使用继承创建与UI相关的模型类,与生成的类分开:
namespace UI.Model {
public class City : Client.Model.City, IDataErrorInfo
{
public String Error { get { return ""; } }
}
}确保在UI上使用UI.Model.City,并且在调用OData服务进行添加操作时,对UI.Model.City类对象执行显式强制转换以转换为Client.Model.City,错误属性将消失:
ODataContainer container = new ODataContainer(new Uri("http://localhost:45666/odata"));
container.AddToCities((Client.Model.City)city);注释:这种方法有自己的Cons,因为它可能导致在不同的名称空间中有相同的类名,所以当使用相同的类名时,通常必须使用完整的命名空间路径。您可以避免在UI模型上使用带有类名的不同前缀/后缀。例如CityViewModel。
发布于 2015-07-20 08:14:33
也许OData客户端钩子可以满足您的要求。见相关问题( dealing with dynamic properties on oData client)
发布于 2015-11-20 05:19:59
我的建议是:
City类的相同名称空间)并实现IdataErrorInfo。Error属性。public string Error {get; set;}modelBuilder.Entity<YourModelClass>().Ignore(x =>x.Error);无需在客户端代码中实现“City”类中的错误属性,因为客户端代码生成器在生成的代码中生成Error属性。
我也有同样的问题,就这样解决了。
https://stackoverflow.com/questions/31483455
复制相似问题