簡體   English   中英

C#中的OData關聯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM