【问题标题】:Entity Passed to WebAPI 2 Method is being Inserted and linked to existing entity传递给 WebAPI 2 方法的实体被插入并链接到现有实体
【发布时间】:2015-09-02 10:04:30
【问题描述】:

我有以下课程(为简洁起见);

   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,但没有任何乐趣。

谁能告诉我我在这里做错了什么?

提前致谢。

【问题讨论】:

  • 我们注意到的一件事是 GetServiceType 实际上是在旋转它自己的上下文,而不是注入的 _service 上下文(从股票的角度来看),这可能会导致问题吗?如果是这样,有人知道如何解决它吗?

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


【解决方案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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    相关资源
    最近更新 更多