本文整理汇总了C#中ODataConventionModelBuilder类的典型用法代码示例。如果您正苦于以下问题:C# ODataConventionModelBuilder类的具体用法?C# ODataConventionModelBuilder怎么用?C# ODataConventionModelBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ODataConventionModelBuilder类属于命名空间,在下文中一共展示了ODataConventionModelBuilder类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Apply
/// <summary>
/// Figures out the key properties and marks them as Keys in the EDM model.
/// </summary>
/// <param name="entity">The entity type being configured.</param>
/// <param name="model">The <see cref="ODataModelBuilder"/>.</param>
public override void Apply(EntityTypeConfiguration entity, ODataConventionModelBuilder model)
{
if (entity == null)
{
throw Error.ArgumentNull("entity");
}
// Suppress the EntityKeyConvention if there is any key in EntityTypeConfiguration.
if (entity.Keys.Any() || entity.EnumKeys.Any())
{
return;
}
// Suppress the EntityKeyConvention if base type has any key.
if (entity.BaseType != null && entity.BaseType.Keys().Any())
{
return;
}
PropertyConfiguration key = GetKeyProperty(entity);
if (key != null)
{
entity.HasKey(key.PropertyInfo);
}
}
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:30,代码来源:EntityKeyConvention.cs
示例2: GetEdmModel
private static IEdmModel GetEdmModel(HttpConfiguration config)
{
var modelBuilder = new ODataConventionModelBuilder(config);
var moviesEntitySet = modelBuilder.EntitySet<Movie>("Movies");
// Now add actions.
// CheckOut
// URI: ~/odata/Movies(1)/ODataActionsSample.Models.CheckOut
ActionConfiguration checkOutAction = modelBuilder.EntityType<Movie>().Action("CheckOut");
checkOutAction.ReturnsFromEntitySet<Movie>("Movies");
// ReturnMovie
// URI: ~/odata/Movies(1)/ODataActionsSample.Models.Return
// Binds to a single entity; no parameters.
ActionConfiguration returnAction = modelBuilder.EntityType<Movie>().Action("Return");
returnAction.ReturnsFromEntitySet<Movie>("Movies");
// CheckOutMany action
// URI: ~/odata/Movies/ODataActionsSample.Models.CheckOutMany
// Binds to a collection of entities. This action accepts a collection of parameters.
ActionConfiguration checkOutManyAction = modelBuilder.EntityType<Movie>().Collection.Action("CheckOutMany");
checkOutManyAction.CollectionParameter<int>("MovieIDs");
checkOutManyAction.ReturnsCollectionFromEntitySet<Movie>("Movies");
// CreateMovie action
// URI: ~/odata/CreateMovie
// Unbound action. It is invoked from the service root.
ActionConfiguration createMovieAction = modelBuilder.Action("CreateMovie");
createMovieAction.Parameter<string>("Title");
createMovieAction.ReturnsFromEntitySet<Movie>("Movies");
modelBuilder.Namespace = typeof(Movie).Namespace;
return modelBuilder.GetEdmModel();
}
开发者ID:ErikWitkowski,项目名称:Simple.OData.Client,代码行数:35,代码来源:ActionStartup.cs
示例3: Register
public static void Register(HttpConfiguration httpConfiguration)
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.Namespace = "ODataV4TestService.Models";
builder.EntitySet<Product>("Products");
builder.EntitySet<SuppliedProduct>("SuppliedProducts");
builder.EntitySet<Supplier>("Suppliers");
builder.EntitySet<Product>("OtherProducts");
builder.ComplexType<Description>();
builder.EntityType<Product>()
.Action("Rate")
.Parameter<int>("Rating");
builder.EntityType<Product>().Collection
.Function("Best")
.ReturnsCollectionFromEntitySet<Product>("Products");
var funcConfig = builder
.EntityType<Product>()
.Function("RelatedProducts")
.SetBindingParameter("product", builder.GetTypeConfigurationOrNull(typeof(Product)))
//.AddParameter("start", new PrimitiveTypeConfiguration(builder, builder.GetTypeConfigurationOrNull(typeof(DateTimeOffset)), typeof(DateTimeOffset)).
.ReturnsCollectionFromEntitySet<Product>("Products");
funcConfig
.Parameter<DateTimeOffset>("start");
funcConfig
.Parameter<DateTimeOffset>("end");
//builder.Function("GetSalesTaxRate")
// .Returns<double>()
// .Parameter<int>("PostalCode");
builder.EntitySet<Account>("Accounts");
builder.EntityType<PaymentInstrument>()
.Collection
.Function("GetCount")
.Returns<int>()
.Parameter<string>("NameContains");
var model = builder.GetEdmModel();
var conventions = ODataRoutingConventions.CreateDefault();
conventions.Insert(0, new AttributeRoutingConvention(model, httpConfiguration));
var server = new BatchServer(httpConfiguration);
httpConfiguration.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: model,
pathHandler: new DefaultODataPathHandler(),
routingConventions: conventions,
batchHandler: new DefaultODataBatchHandler(server));
httpConfiguration.MessageHandlers.Add(new TracingMessageHandler());
}
开发者ID:iambmelt,项目名称:Vipr,代码行数:60,代码来源:WebApiConfig.cs
示例4: Apply_Doesnot_Override_UserConfiguration
public void Apply_Doesnot_Override_UserConfiguration()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var vehicles = builder.EntitySet<Vehicle>("vehicles");
var car = builder.AddEntityType(typeof(Car));
var paintAction = vehicles.EntityType.Action("Paint");
paintAction.HasActionLink(ctxt => new Uri("http://localhost/ActionTestWorks"), followsConventions: false);
ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention();
convention.Apply(paintAction, builder);
IEdmModel model = builder.GetEdmModel();
var vehiclesEdmSet = model.EntityContainer.FindEntitySet("vehicles");
var carEdmType = model.FindDeclaredType("System.Web.OData.Builder.TestModels.Car") as IEdmEntityType;
var paintEdmAction =
model.GetAvailableProcedures(
model.FindDeclaredType("System.Web.OData.Builder.TestModels.Car") as IEdmEntityType).Single()
as IEdmAction;
Assert.NotNull(paintEdmAction);
HttpConfiguration configuration = new HttpConfiguration();
configuration.Routes.MapODataServiceRoute(model);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
request.SetConfiguration(configuration);
ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(paintEdmAction);
var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = vehiclesEdmSet, Url = request.GetUrlHelper() };
var entityContext = new EntityInstanceContext(serializerContext, carEdmType.AsReference(), new Car { Model = 2009, Name = "Contoso" });
Uri link = actionLinkBuilder.BuildActionLink(entityContext);
Assert.Equal("http://localhost/ActionTestWorks", link.AbsoluteUri);
}
开发者ID:nicholaspei,项目名称:aspnetwebstack,代码行数:34,代码来源:ActionLinkGenerationConventionTest.cs
示例5: GetEdmModel
// Builds the EDM model
private static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
builder.EntitySet<Order>("Orders");
return builder.GetEdmModel();
}
开发者ID:nickgoodrow,项目名称:ODataSamples,代码行数:8,代码来源:WebApiConfig.cs
示例6: GetEdmModel
private IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("FormatCustomers");
builder.Singleton<Customer>("This"); // Singleton
return builder.GetEdmModel();
}
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:7,代码来源:DollarFormatTest.cs
示例7: Validate_DepthChecks_DollarLevels
public void Validate_DepthChecks_DollarLevels(string expand, int maxExpansionDepth)
{
// Arrange
var validator = new SelectExpandQueryValidator();
var builder = new ODataConventionModelBuilder();
builder.EntitySet<ODataLevelsTest.LevelsEntity>("Entities");
IEdmModel model = builder.GetEdmModel();
var context = new ODataQueryContext(model, typeof(ODataLevelsTest.LevelsEntity));
var selectExpandQueryOption = new SelectExpandQueryOption(null, expand, context);
selectExpandQueryOption.LevelsMaxLiteralExpansionDepth = 1;
// Act & Assert
Assert.Throws<ODataException>(
() => validator.Validate(
selectExpandQueryOption,
new ODataValidationSettings { MaxExpansionDepth = maxExpansionDepth }),
String.Format(
CultureInfo.CurrentCulture,
"The request includes a $expand path which is too deep. The maximum depth allowed is {0}. " +
"To increase the limit, set the 'MaxExpansionDepth' property on EnableQueryAttribute or ODataValidationSettings.",
maxExpansionDepth));
Assert.DoesNotThrow(
() => validator.Validate(
selectExpandQueryOption,
new ODataValidationSettings { MaxExpansionDepth = maxExpansionDepth + 1 }));
}
开发者ID:shailendra9,项目名称:WebApi,代码行数:27,代码来源:SelectExpandQueryValidatorTest.cs
示例8: ParameterAliasNodeTranslatorTest
public ParameterAliasNodeTranslatorTest()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<ParameterAliasCustomer>("Customers");
builder.EntitySet<ParameterAliasOrder>("Orders");
builder.EntityType<ParameterAliasCustomer>().Function("CollectionFunctionCall")
.ReturnsCollection<int>().Parameter<int>("p1");
builder.EntityType<ParameterAliasCustomer>().Function("EntityCollectionFunctionCall")
.ReturnsCollectionFromEntitySet<ParameterAliasCustomer>("Customers").Parameter<int>("p1");
builder.EntityType<ParameterAliasCustomer>().Function("SingleEntityFunctionCall")
.Returns<ParameterAliasCustomer>().Parameter<int>("p1");
builder.EntityType<ParameterAliasCustomer>().Function("SingleEntityFunctionCallWithoutParameters")
.Returns<ParameterAliasCustomer>();
builder.EntityType<ParameterAliasCustomer>().Function("SingleValueFunctionCall")
.Returns<int>().Parameter<int>("p1");
_model = builder.GetEdmModel();
_customersEntitySet = _model.FindDeclaredEntitySet("Customers");
_customerEntityType = _customersEntitySet.EntityType();
_parameterAliasMappedNode = new ConstantNode(123);
}
开发者ID:ahmetgoktas,项目名称:aspnetwebstack,代码行数:26,代码来源:ParameterAliasNodeTranslatorTest.cs
示例9: GetSampleModel
private static IEdmModel GetSampleModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Employee>("employees");
builder.EntitySet<WorkItem>("workitems");
return builder.GetEdmModel();
}
开发者ID:tlycken,项目名称:aspnetwebstack,代码行数:7,代码来源:EntityTypeTest.cs
示例10: GetModel
public override IEdmModel GetModel(Type elementClrType, HttpRequestMessage request,
HttpActionDescriptor actionDescriptor)
{
// Get model for the request
IEdmModel model = request.ODataProperties().Model;
if (model == null)
{
// user has not configured anything or has registered a model without the element type
// let's create one just for this type and cache it in the action descriptor
model = actionDescriptor.Properties.GetOrAdd("System.Web.OData.Model+" + elementClrType.FullName, _ =>
{
ODataConventionModelBuilder builder =
new ODataConventionModelBuilder(actionDescriptor.Configuration, isQueryCompositionMode: true);
builder.EnableLowerCamelCase();
EntityTypeConfiguration entityTypeConfiguration = builder.AddEntityType(elementClrType);
builder.AddEntitySet(elementClrType.Name, entityTypeConfiguration);
IEdmModel edmModel = builder.GetEdmModel();
Contract.Assert(edmModel != null);
return edmModel;
}) as IEdmModel;
}
Contract.Assert(model != null);
return model;
}
开发者ID:tanjinfu,项目名称:WebApiODataSamples,代码行数:26,代码来源:MyEnableQueryAttribute.cs
示例11: ConfigureWebApi
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureWebApi(IAppBuilder app)
{
var config = new HttpConfiguration();
// Web API routes
config.MapHttpAttributeRoutes(); //NB Must come before OData route mapping
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
// OData: Create the OData model. Here, we're using the convention model builder that will use OData
// convention defaults for model creation and routing.
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
// All entity properties should be in lower camel case
builder.EnableLowerCamelCase();
// Because PersonSearchHit inherits from SearchHit, we'll ignore it.
// This gets around the convention builder's decision to create an entity out of the SearchHit object.
builder.Ignore<PersonSearchHit>();
// Create two entity sets:
// One for search features and one that will retrieve a given person.
builder.EntitySet<IndexSearch>("Search");
builder.EntitySet<Person>("People");
// OData model registration and route creation
config.MapODataServiceRoute("ODataRoute", null, builder.GetEdmModel());
// Set up the bearer token that will be required to do OData calls.
WebApiConfigBearerToken.Configure(config);
app.UseWebApi(config);
}
开发者ID:tyler-technologies,项目名称:PeopleWhoMatterTrainingWebApp,代码行数:33,代码来源:Startup.WebApi.cs
示例12: GetModel
private static IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
EntitySetConfiguration<OrderByCustomer> customers = builder.EntitySet<OrderByCustomer>("OrderByCustomers");
EntitySetConfiguration<OrderByOrder> orders = builder.EntitySet<OrderByOrder>("OrderByOrders");
return builder.GetEdmModel();
}
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:7,代码来源:OrderByTests.cs
示例13: GetModel
private static IEdmModel GetModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
EntitySetConfiguration<Trade> tradesConfiguration = builder.EntitySet<Trade>("Trades");
//Add bound function
var boundFunction = tradesConfiguration.EntityType.Collection.Function("GetTradingVolume");
boundFunction.Parameter<string>("productName");
boundFunction.Parameter<Country>("portingCountry");
boundFunction.Returns<long?>();
//Add bound function
boundFunction = tradesConfiguration.EntityType.Collection.Function("GetTopTrading");
boundFunction.Parameter<string>("productName");
boundFunction.ReturnsFromEntitySet<Trade>("Trades");
boundFunction.IsComposable = true;
//Add unbound function
var unboundFunction = builder.Function("GetTradeByCountry");
unboundFunction.Parameter<Country>("portingCountry");
unboundFunction.ReturnsCollectionFromEntitySet<Trade>("Trades");
builder.Namespace = typeof(Country).Namespace;
return builder.GetEdmModel();
}
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:26,代码来源:ParameterAliasTest.cs
示例14: Register
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
// 将 Web API 配置为仅使用不记名令牌身份验证。
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//有关OData
//使用ODataConventionModelBuilder创建EDM使用了一些惯例
//如果要对创建EDM有更多的控制,使用ODataModelBuilder
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");//创建EntityDataModel(EDM)
builder.EntitySet<Supplier>("Suppliers");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "odata",
model: builder.GetEdmModel());
}
开发者ID:zidanfei,项目名称:OData,代码行数:27,代码来源:WebApiConfig.cs
示例15: IgnoreOfT_Should_AddToListOfIgnoredTypes
public void IgnoreOfT_Should_AddToListOfIgnoredTypes()
{
var builder = new ODataConventionModelBuilder();
builder.Ignore<object>();
Assert.True(builder.IsIgnoredType(typeof(object)));
}
开发者ID:naulizzang,项目名称:aspnetwebstack,代码行数:7,代码来源:ODataConventionModelBuilderTests.cs
示例16: GetEdmModel
private static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<ResponseDataModel>("Users");
builder.EntitySet<CustomerCardAdministrationDataModel>("CustomerCards");
return builder.GetEdmModel();
}
开发者ID:TS-Projects,项目名称:TechSupportWebApi,代码行数:7,代码来源:ODataConfig.cs
示例17: GetModel
private static IEdmModel GetModel()
{
const string UsersSet = "Users";
const string FriendshipsSet = "Friendships";
const string TweetsSet = "Tweets";
var builder = new ODataConventionModelBuilder();
var users = builder.EntitySet<User>(UsersSet);
builder.EntitySet<Friendship>(FriendshipsSet);
builder.EntitySet<Tweet>(TweetsSet);
users.EntityType.Ignore(u => u.Password);
users.EntityType.Ignore(u => u.Email);
// nameof(...) == "Login"
builder.Namespace = "TwitterApi";
var login = users.EntityType.Collection.Action(nameof(UsersController.Login));
login.Parameter<string>(nameof(User.Password));
login.Parameter<string>(nameof(User.Email));
login.Returns<AuthenticateResponse>();
var me = users.EntityType.Collection.Function(nameof(UsersController.Me));
me.ReturnsFromEntitySet<User>(UsersSet);
return builder.GetEdmModel();
}
开发者ID:mimipaskova,项目名称:Azure-Tech-Entrepreneurship-Course,代码行数:26,代码来源:WebApiConfig.cs
示例18: GetInheritanceModel
private static IEdmModel GetInheritanceModel(HttpConfiguration config)
{
ODataModelBuilder builder = new ODataConventionModelBuilder(config);
var baseEntitySet = builder.EntitySet<BaseEntity>("BaseEntity");
var derivedEntityType = builder.EntityType<DerivedEntity>().DerivesFrom<BaseEntity>();
return builder.GetEdmModel();
}
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:7,代码来源:EntryMetadataTests.cs
示例19: Apply_DoesnotRemoveProperty_TypeIsDataContractAndPropertyHasDataMember
public void Apply_DoesnotRemoveProperty_TypeIsDataContractAndPropertyHasDataMember()
{
// Arrange
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
Mock<PropertyInfo> property = new Mock<PropertyInfo>();
property.Setup(p => p.Name).Returns("Property");
property.Setup(p => p.PropertyType).Returns(typeof(int));
property.Setup(p => p.GetCustomAttributes(It.IsAny<Type>(), It.IsAny<bool>())).Returns(new Attribute[]
{
new IgnoreDataMemberAttribute(),
new DataContractAttribute()
});
property.Setup(p => p.GetCustomAttributes(It.IsAny<bool>())).Returns(new Attribute[]
{ new IgnoreDataMemberAttribute(),
new DataContractAttribute()
});
Mock<Type> type = new Mock<Type>();
type.Setup(t => t.GetCustomAttributes(It.IsAny<Type>(), It.IsAny<bool>())).Returns(new[] { new DataContractAttribute() });
Mock<StructuralTypeConfiguration> structuralType = new Mock<StructuralTypeConfiguration>(MockBehavior.Strict);
structuralType.Setup(s => s.ClrType).Returns(type.Object);
Mock<PropertyConfiguration> primitiveProperty = new Mock<PropertyConfiguration>(property.Object, structuralType.Object);
// Act
new IgnoreDataMemberAttributeEdmPropertyConvention().Apply(primitiveProperty.Object, structuralType.Object, builder);
// Assert
structuralType.Verify();
}
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:32,代码来源:IgnoreDataMemberAttributeEdmPropertyConventionTests.cs
示例20: LowerCamelCaser_ProcessReflectedAndDataMemberAttributePropertyNames
public void LowerCamelCaser_ProcessReflectedAndDataMemberAttributePropertyNames()
{
// Arrange
var builder = new ODataConventionModelBuilder().EnableLowerCamelCase(
NameResolverOptions.ProcessReflectedPropertyNames | NameResolverOptions.ProcessDataMemberAttributePropertyNames);
EntityTypeConfiguration<LowerCamelCaserEntity> entityTypeConfiguration = builder.EntitySet<LowerCamelCaserEntity>("Entities").EntityType;
entityTypeConfiguration.Property(b => b.ID).Name = "iD";
entityTypeConfiguration.Property(d => d.Name).Name = "Name";
entityTypeConfiguration.EnumProperty(d => d.Color).Name = "Something";
ComplexTypeConfiguration<LowerCamelCaserComplex> complexTypeConfiguration = builder.ComplexType<LowerCamelCaserComplex>();
complexTypeConfiguration.CollectionProperty(c => c.Notes).Name = "MyNotes";
// Act
IEdmModel model = builder.GetEdmModel();
// Assert
IEdmEntityType lowerCamelCaserEntity =
Assert.Single(model.SchemaElements.OfType<IEdmEntityType>().Where(e => e.Name == "LowerCamelCaserEntity"));
IEdmComplexType lowerCamelCaserComplex =
Assert.Single(model.SchemaElements.OfType<IEdmComplexType>().Where(e => e.Name == "LowerCamelCaserComplex"));
Assert.Equal(5, lowerCamelCaserEntity.Properties().Count());
Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "iD"));
Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "Name"));
Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "details"));
Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "Something"));
Assert.Single(lowerCamelCaserEntity.Properties().Where(p => p.Name == "complexProperty"));
Assert.Equal(2, lowerCamelCaserComplex.Properties().Count());
Assert.Single(lowerCamelCaserComplex.Properties().Where(p => p.Name == "price"));
Assert.Single(lowerCamelCaserComplex.Properties().Where(p => p.Name == "MyNotes"));
}
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:30,代码来源:LowerCamelCaserTest.cs
注:本文中的ODataConventionModelBuilder类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论