代码之家  ›  专栏  ›  技术社区  ›  HAdes

在LinqToSql中,是否可以有一个自定义的Insert方法来自动同步主键?

  •  0
  • HAdes  · 技术社区  · 16 年前

    我试图简单地从sql server返回@@Identity,然后将其分配给ID,但这会导致更改通知,LinqToSql认为它已经更改,即使它只是ID。

    因此,基本上我需要一种通过sp在插入时分配主键的方法,而不会触发更改通知。

    谢谢。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Ruben    16 年前

    DataContext 称为 InsertEntity (其中 实体 是你们班的名字。在此方法中,您必须手动调用SP,但随后您可以将返回值映射到实体的属性,Linq to SQL将遵守这一点。

    例如:

    public partial class YourDataContext
    {
        partial void InsertYourEntity(YourEntity entity)
        {
            using (DbCommand cmd = this.Connection.CreateCommand())
            {
                ... // set the parameters and SP name here
    
                cmd.ExecuteNonQuery();
    
                entity.Id = (int) someParameter.Value;
            }
        }
    }
    

    请注意,这不会抑制任何 IdChanging IdChanged 事件(因为它确实发生了变化,数据绑定可能取决于适当的通知)。然而,呼叫 SubmitChanges 两次会 原因a Insert Update ,作为第二 提交更改 不会看到实体被更改。

        2
  •  0
  •   guercheLE    16 年前

    设置“使用运行时”后,实体将发出一条类似下面的sql语句,尝试在存储过程实现中模仿它。

    DECLARE @output TABLE([SurrogateKey] UniqueIdentifier)
    DECLARE @id UniqueIdentifier
    
    INSERT INTO [identity].[AddressTypes]([Name])
    OUTPUT INSERTED.[SurrogateKey] INTO @output
    VALUES (@p0)
    
    SELECT @id = SurrogateKey FROM @output
    
    SELECT [t0].[SurrogateKey], [t0].[LastUpdatedOn], [t0].[LastUpdatedBy]
    FROM [identity].[AddressTypes] AS [t0]
    WHERE [t0].[SurrogateKey] = (@id)
    -- @p0: Input VarChar (Size = 5; Prec = 0; Scale = 0) [Other]
    -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1