【问题标题】:Can't submit new object to WCF DataService because of Primary Key constraint由于主键约束,无法向 WCF DataService 提交新对象
【发布时间】:2011-02-18 17:26:48
【问题描述】:

我有一个使用 Guid 进行 PK 的 SQL 数据库,在插入时,它会生成一个 NewId()。我有一个指向该数据库的 EF 数据上下文设置,其主键设置为 Entity key:true、Setter:private 和 StoreGeneratedPattern:Identity,因为我希望 DB 管理键并且没有代码设置 PK 属性。

我有一个 OData (System.Web.Data.Services.DataService) 端点来访问这些数据(就像:Hanselman did

我有另一个应用程序具有对此服务的服务引用。在尝试从此引用(即产品)创建新对象时,ProductId 主键在执行时默认为 Guid.Empty

var serviceEntities = new ServiceEntities(serviceUri); //OData endpoint

var product = new Product();
product.Name = "New Product";

serviceEntities.AddToProducts(product);
serviceEntities.SaveChanges(); // error happens here

调试时,我查看 Product.ProductId 属性,它设置为 Guid.Empty。当调用 SaveChanges 时,我不希望将 ProductId 字段发送到服务。我得到的回应是:

错误处理请求流。 属性“ProductId”是只读的 属性,无法更新。请 确保该属性不是 存在于请求负载中。

有没有办法做到这一点,或者我可以做些什么来正确地进行此设置并且仍然让数据库生成密钥。

这里的设置与上面的产品示例相同。

【问题讨论】:

    标签: wcf entity-framework odata wcf-data-services


    【解决方案1】:

    我最终做的是添加一个ChangeInterceptor。这可行,但不是首选方式。

    [ChangeInterceptor("Products")]
    public void OnChangeApplications(Product product, UpdateOperations operations)
    {
        if (operations != UpdateOperations.Add) return;
    
        if (product.ProductId == Guid.Empty)
        {
            product.ProductId = Guid.NewGuid();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 2011-04-07
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      相关资源
      最近更新 更多