传递给WebAPI 2的实体方法正在被插入并链接到现有的实体
本文关键字:实体 插入 链接 WebAPI 方法 | 更新日期: 2023-09-27 18:11:00
我有以下类(简化为简洁);
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);
}
。对象正在击中API post方法,然而,每次它插入一个新的DeviceType而不是链接到有效的一个?
我已经尝试过了,没有从数据库中获得DeviceType,没有快乐。
谁能告诉我我在这里做错了什么?这是因为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对象:
Stock objStock = new Stock();
objStock.DeviceTypesId = deviceid;
objStock.Date = DateTime.UtcNow;
objStock.Quantity = quantity;
其中deviceid
为数据库中已经存在的DeviceTypes对象的id