传递给WebAPI 2的实体正在插入并链接到现有实体

时间:2015-09-02 10:04:31

标签: c# entity-framework entity-framework-6

我有以下课程(简化为breivity);

   public partial class Stock 
{
    [Column("StockId")]
    [JsonProperty(PropertyName = "stockid")]
    public int ID { get; set; }
    public DateTime Date { get; set; }
    public int Quantity { get; set; }

    [JsonProperty(PropertyName = "devicecode")]
    public DeviceTypes Device { get; set; }
}

public partial class DeviceTypes
{
    [Column("id")]
    [JsonProperty(PropertyName = "devicetypeid")]
    public int ID { get; set; }
    public string DeviceType { get; set; }
}

仅为完整性VS显示表格组成如下;

 CREATE TABLE [dbo].[Stocks] (
    [StockId]     INT            IDENTITY (1, 1) NOT NULL,
    [Date]        DATETIME       NOT NULL,
    [Quantity]    INT            NOT NULL,
    [Device_ID]   INT            NULL,
    CONSTRAINT [PK_dbo.Stocks] PRIMARY KEY CLUSTERED ([StockId] ASC),
    CONSTRAINT [FK_dbo.Stocks_dbo.DeviceTypes_Device_ID] FOREIGN KEY ([Device_ID]) REFERENCES [dbo].[DeviceTypes] ([id])
);

CREATE TABLE [dbo].[DeviceTypes] (
    [id]         INT          IDENTITY (1, 1) NOT NULL,
    [DeviceType] VARCHAR (50) NOT NULL,
    CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ([id] ASC)
);

现在当我通过例如

Stock objStock = new Stock();
objStock.Device = new DeviceTypes { ID = deviceid };
objStock.Date = DateTime.UtcNow;
objStock.Quantity = quantity; 

到api方法如下;

    public IHttpActionResult Post([FromBody]Stock stock)
    {
        //done as a double check 
        var deviceType = _Service.GetDeviceType(stock.Device.ID);
        stock.Device = deviceType;

        _Service.Insert(stock);

        return Ok(stock.ID);
    }

即。但是,每次它插入一个新的DeviceType而不是链接到有效的一个时,该对象是否会触及API post方法?

我已尝试过,无需从数据库中获取DeviceType,但没有任何乐趣。

有人可以告诉我,我在做错了吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

这是因为EF认为您也传递了新的DeviceTypes对象。 您可以在stock对象中为此DeviceTypes对象添加一个标识符,该对象包含预先存在的DeviceTypes对象的ID:

public partial class Stock 
{
    [Column("StockId")]
    [JsonProperty(PropertyName = "stockid")]
    public int ID { get; set; }
    public DateTime Date { get; set; }
    public int Quantity { get; set; }

    [JsonProperty(PropertyName = "devicecode")]
    public DeviceTypes Device { get; set; }
    [ForeignKey("Device")]
    public int DeviceTypesId {get; set;} // new field, holds existing devicetypes id
}

然后传递股票对象:

Stock objStock = new Stock();
objStock.DeviceTypesId = deviceid;
objStock.Date = DateTime.UtcNow;
objStock.Quantity = quantity; 

其中deviceid是数据库中已存在的DeviceTypes对象的id。