I have the following classes (simplified for 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; }
}
just for fullness VS shows the table composition to be as follows;
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)
);
Now when I pass across for example
Stock objStock = new Stock();
objStock.Device = new DeviceTypes { ID = deviceid };
objStock.Date = DateTime.UtcNow;
objStock.Quantity = quantity;
to the api method which is as follows;
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);
}
i.e. the object is hitting the API post method, however,everytime it is inserting a new DeviceType instead of linking to the valid one?
I have tried with and without getting the DeviceType from the db with no joy.
Can someone tell me what I am doing wrong here please?
Thanks in advance.