[英]OData Associations In C#
当我遇到有关关联的这一部分时,我正在Odata.org上阅读有关OData源的信息。
关联定义两个或多个实体类型(例如,Employee WorksFor Department)之间的关系。 关联实例分组在关联集中。 导航属性是绑定到特定关联的实体类型上的特殊属性,可用于引用实体的关联。
最后,所有实例容器(实体集和关联集)都被分组在一个实体容器中。
将以上段落放入OData术语中,OData服务公开的提要由实体集或标识实体集合的实体类型上的导航属性表示。 例如,实体集标识由URI http://services.odata.org/OData/OData.svc/Products或实体的“产品”导航属性中确定的集合http://services.odata.org /OData/OData.svc/Categories(1)/Products标识OData服务公开的条目的提要。
我正在使用Visual Studio 2012在C#中制作OData服务,并想使用提到的URL功能。 但是我不知道如何设置它。 有人知道怎么做这个吗?
这是我的代码:
public class AssociationTest : DataService<ServiceContext>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
}
public class ServiceContext
{
CategoryList _categories = new CategoryList();
public IQueryable<Category> CategorySet
{
get{return _categories.AsQueryable();}
}
ProductList _products = new ProductList();
public IQueryable<Product> ProductSet
{
get{return _products.AsQueryable();}
}
}
[System.Data.Services.Common.DataServiceKeyAttribute("ID")]
public class Category
{
public string Type
{
get;
set;
}
public int ID
{
get;
set;
}
}
public class CategoryList : List<Category>
{
public CategoryList()
: base()
{
Add(new Category { Type = "Hardware", ID = 0 });
Add(new Category { Type = "Software", ID = 1 });
}
}
[System.Data.Services.Common.DataServiceKeyAttribute("ID")]
public class Product
{
public string Name
{
get;
set;
}
public int ID
{
get;
set;
}
public int CategoryID
{
get;
set;
}
}
public class ProductList:List<Product>
{
public ProductList()
: base()
{
Add(new Product { Name = "Computer", ID = 0, CategoryID = 0 });
Add(new Product { Name = "Phone", ID = 1, CategoryID = 0 });
Add(new Product { Name = "Outlook", ID = 2, CategoryID = 1 });
Add(new Product { Name = "Excel", ID = 3, CategoryID = 1 });
}
}
不用使用外键对Product-> Category之间的关系进行建模,您可以使服务模型直接指向产品的类别。 我的意思是代替这个:
public class Product
{
// ...
public int CategoryID
{
get;
set;
}
}
您可以像这样建模:
public class Product
{
// ...
public Category ProductCategory
{
get;
set;
}
}
如果以这种方式设置模型,则WCF数据服务反射提供程序应自动在Product上创建导航属性,并在模型中创建必要的关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.