0

I am currently using OData V4 and wish to join 2 tables Account and Product:

The tables are as follows: Account: Id, Name, Address, ColorCode,

Product: Id, AccountId

AccountId in the Product table is a foreign key mapped to the Id field in the Account table

In my builder I have :

var ProductType= builder.EntityType<Product>();

When I build the Product entity I wish to get the "ColorCode" values from the Account entity.

How can i establish this relationship in the model builder?

I would like the product class to look like this:

public  class Product
{
    public string Id { get; set; }
    public string AccountId { get; set; }
    public string ColorCode { get; set; }

}
4

1 回答 1

1

OData 使您能够定义实体之间的关系。您似乎正在使用 Web API 2.2 for OData V4 来编写您的服务。在这种情况下,您可以像这样在 Products 和 Accounts 之间建立关系:

首先,在 Products 的 POCO 类的定义中,您需要为其帐户添加一个导航属性:

public class Product{
    public int Id {get;set;}
    public string AccountId {get;set;}
    public Account Account {get;set;} // define "Account" as a navigation property of Product

public class Account{
    public int Id {get;set;}
    public string Name {get;set;}
    public Address Address {get;set;} // Address may be a complex type
    public int ColorCode {get;set;}
}

然后在继承自 的类中,在以下位置DbContext添加有关两个实体的信息:

public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<Account> Accounts { get; set; }

最后在 WebApiConfig.cs 中,您可以ODataConventionModelBuilder根据需要定义使用的模型。模型构建器将自动识别 POCO 类中的关系并为您生成模型。

服务建立后,在客户端,客户端发送这样的请求以获取产品和其帐户的颜色代码:

GET http://host/service/Products?$expand=Account($select=ColorCode)

可以在此处查看示例:http : //services.odata.org/v4/(S(xrtmlkz1igiqidututicmb2t))/TripPinServiceRW/People ?$expand=Trips($select=TripId)

于 2014-12-03T05:08:59.830 回答