0

这是我使用微风/角度/EF的试验项目。我不明白为什么会出现此错误,因为我认为我以前使用相同的结构。

public class TshirtOrder
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    [ForeignKey("Type")]
    public int TshirtTypeId { get; set; }
    public virtual TshirtType Type { get; set; }
    [ForeignKey("Size")]
    public int TshirtSizeId { get; set; }
    public virtual TshirtSize Size { get; set; }
    public double UnitPrice { get; set; }
    public int Quantity { get; set; }

    [ForeignKey("TshirtOrder")]
    public int TshirtOrderId { get; set; }
    public TshirtOrder TshirtOrder { get; set; }
}

表定义如下所示:

CREATE TABLE [dbo].[TshirtOrder] (
    [Id]         INT            IDENTITY (1, 1) NOT NULL,
    [Name]       NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_dbo.TshirtOrder] PRIMARY KEY CLUSTERED ([Id] ASC)
);

CREATE TABLE [dbo].[OrderItem] (
    [Id]            INT        IDENTITY (1, 1) NOT NULL,
    [TshirtTypeId]  INT        NOT NULL,
    [TshirtSizeId]  INT        NOT NULL,
    [UnitPrice]     FLOAT (53) NOT NULL,
    [Quantity]      INT        NOT NULL,
    [TshirtOrderId] INT        NOT NULL,
    CONSTRAINT [PK_dbo.OrderItem] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_dbo.OrderItem_dbo.TshirtType_TshirtTypeId] FOREIGN KEY ([TshirtTypeId]) REFERENCES [dbo].[TshirtType] ([Id]) ON DELETE CASCADE,
    CONSTRAINT [FK_dbo.OrderItem_dbo.TshirtSize_TshirtSizeId] FOREIGN KEY ([TshirtSizeId]) REFERENCES [dbo].[TshirtSize] ([Id]) ON DELETE CASCADE,
    CONSTRAINT [FK_dbo.OrderItem_dbo.TshirtOrder_TshirtOrderId] FOREIGN KEY ([TshirtOrderId]) REFERENCES [dbo].[TshirtOrder] ([Id]) ON DELETE CASCADE
);

这是它在 Breeze 数据上下文中的保存方式:

function _createTshirtOrder() {
    var order = manager.createEntity("TshirtOrder");

    order.orderItems.push(createOrderItem(lookups.tshirtTypes[0], lookups.tshirtSizes[0], 10));
    common.saveEntity(order);
    return order;

    function createOrderItem(type, size, unitPrice) {
        var item = manager.createEntity("OrderItem");
        item.type = type;
        item.size = size;
        item.unitPrice = unitPrice;
        item.quantity = 0;
        return item;
    }
}

这是确切的错误:

{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.OrderItem_dbo.TshirtOrder_TshirtOrderId\". The conflict occurred in database \"dbbb\", table \"dbo.TshirtOrder\", column 'Id'.\r\nThe statement has been terminated."}

那么,问题出在哪里?

4

1 回答 1

4

我不知道您的“saveEntity”方法是什么样的,但我猜它会调用

entityManager.saveChanges([order]);

如果是这样,那么问题是您只保存订单而不是 orderItem,因为您告诉它只保存一个订单。Breeze 跟踪对 entityManager 的任何更改,因此更好的解决方案通常是让 Breeze 为您解决。IE

entityManager.saveChanges();  or entityManager.saveChanges(null, ... );

这将在 entityManager 中保存所有添加、修改或删除的记录。

或者,您可以指定要保存的所有实体。

entityManager.saveChanges([order, orderItem1, orderItem2, ... ]);
于 2013-11-07T16:22:44.157 回答