Asp.Net WebApi OData v4 - 将实体与相关实体一起保存

时间:2016-02-23 12:49:57

标签: c# entity-framework asp.net-web-api odata odata-v4

考虑以下实体

public class Supplier
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }  

    public int? SupplierId { get; set; }
    public virtual Supplier Supplier { get; set; }
}

根据上述代码,供应商实体可以拥有零个或多个产品。 在上述实体中,ID由实体框架自动生成。

我正在使用Odata V4客户端代码生成器。

客户代码:

Supplier s = new Supplier{...}
OdataContext.AddToSuppliers(s);

Product p = new Product{...}
p.SupplierId = s.Id;
OdataContext.AddToProduct (p);

OdataContext.SaveChanges();

供应商总监:

public async Task<IHttpActionResult> Post(Supplier supplier)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    db.Supplier.Add(supplier);
    await db.SaveChangesAsync();
    return Created(supplier);
}

产品总监:

public async Task<IHttpActionResult> Post(Product product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    db.Products.Add(product);
    await db.SaveChangesAsync();
    return Created(product);
}

保存更改后,我收到错误消息:

  

INSERT语句与FOREIGN KEY约束冲突。

错误的原因是Product实体尚未拥有SupplierId数据库生成密钥。

那么在保存记录时如何将SupplierId添加到Product实体? 任何人都可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

好的,谢谢你的澄清。假设您使用的是SQL Server,您的Int Id列将按惯例成为标识列。从这个角度来看,产品可以有0或1个供应商。

要向新供应商添加新产品,您可以执行以下操作:

Supplier s = new Supplier
{
    Name = "mySupplier"
}

Product p = new Product
{
    Name = "myname",
    Price = 123.45,
    Category = "myCategory",
    Supplier = s
}

OdataContext.Products.Add(p);
OdataContext.SaveChanges();

将现有供应商添加到产品中:

// select a supplierId or search by name
var supplier = OdataContext.Suppliers.FirstOrDefault(s => s.Name == nameToFind);
if (supplier == null) // Handle no match

Product p = new Product
{
    Name = "myname",
    Price = 123.45,
    Category = "myCategory",
    SupplierId = supplier.Id
}

OdataContext.Products.Add(p);
OdataContext.SaveChanges();

答案 1 :(得分:0)

使用OData V4,您可以尝试深度插入方法。深度插入允许在一个请求中创建相关实体的树。 http://docs.oasis-open.org/odata/odata/v4.0/os/part1-protocol/odata-v4.0-os-part1-protocol.html#_Toc372793718

答案 2 :(得分:0)

我认为OData Client不支持深度插入。所以另一种选择是对请求体使用WebClient和JSON序列化器,如下所示。父单元和子实体都将在单个http请求中创建,外键将相应更新 -

var product = new ProductService.Models.Product()
        {
            Name = "My Car",
            Category = "Auto",
            Price = 4.85M
        };

        var supplier = new ProductService.Models.Supplier()
        {
            Name = "My Name"
        };

        //Add product to supplier
        supplier.Products.Add(product);

        WebClient client = new WebClient();
        client.BaseAddress = "http://example.com/OData";
        client.Headers.Add("Content-Type", "application/json");

        //Serialize supplier object
        var serializer = new JavaScriptSerializer();
        var serializedResult = serializer.Serialize(supplier);

        //Call the service
        var result = client.UploadString("http://example.com/OData/Suppliers", serializedResult.ToString());

供应商控制器中的后期行动 -

public async Task<IHttpActionResult> Post(Supplier supplier)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.Suppliers.Add(supplier);
        await db.SaveChangesAsync();
        return Created(supplier);
    }
相关问题