对于Web 2和OData v3,特别是ODataConventionModelBuilder,我遇到了一个奇怪的问题。我的WebApiConfig.cs中有以下代码
// Web API configuration and services
var builder = new ODataConventionModelBuilder();
// Adding all the entity sets here, then complex types, custom actions, ...
builder.EntitySet<Address>("Addresses");
/* ... */
builder.AddComplexType(typeof(CustomerSearchResultDto));
/* ... */
var customerSearchAction = builder.Entity<Customer>().Collection.Action("Search");
patientSearchAction.Parameter<string>("pattern");
patientSearchAction.Parameter<bool>("searchDeactivated");
// These are the interfaces that some entities implement. These MUST NOT be put into the model
var interfaces = typeof(ICustomer).Assembly.GetTypes().Where(t => t.IsInterface).ToArray();
builder.Ignore(interfaces);
// Building models
var model = builder.GetEdmModel();
config.Routes.MapODataServiceRoute("odata", "odata", model);这些模型构建良好,无一例外。但是一些实体实现的接口被转换成复杂的类型,这当然是荒谬的,并且会在客户端造成相当大的名称空间混乱。以下是生成的元数据的摘录(服务:1111/$元数据)
<ComplexType Name="IAddress">
<Property Name="Street1" Type="Edm.String" />
<Property Name="Street2" Type="Edm.String" />
<Property Name="Zip" Type="Edm.String" />
<Property Name="City" Type="Edm.String" />
<Property Name="Country" Type="Edm.String" />
</ComplexType>我也尝试使用builder.Ignore<IAddress>,但没有效果。我做错了什么?
发布于 2015-01-30 00:07:18
我找到了更好的解决办法。在WebApiConfig.cs中,我为每个实体做了以下工作:
builder.EntitySet<Address>("Addresses").EntityType.DerivesFromNothing();如果实体派生自另一个实体,则使用DerivesFrom()方法。为了避免名称空间与复杂类型发生冲突,我使用DTO。因为我有很多这样的代码,所以我只需要像这样批量添加它们(使用反射):
var builderMethod = builder.GetType().GetMethod("ComplexType");
foreach (var type in typeof (WebApiConfig).Assembly.GetTypes().Where(x => x.Name.EndsWith("Dto")))
{
var genericMethod = builderMethod.MakeGenericMethod(type);
genericMethod.Invoke(builder, null);
}这个效果很好。
发布于 2015-01-08 07:07:43
我想您有一个定义为IAddress的属性,例如:
public class Customer
{
public int CustomerId { get; set; }
public IAddress Address { get; set; }
...
}因此,builder.Ignore(interfaces);不工作。
如果是的话,你可以:
Ignore该属性。https://stackoverflow.com/questions/27816302
复制相似问题