Use linq to generate direct update without select

前端 未结 7 896
感情败类
感情败类 2020-11-29 05:34

G\'day everyone.

I\'m still learning LINQ so forgive me if this is naive. When you\'re dealing with SQL directly, you can generate update commands with conditionals

7条回答
  •  渐次进展
    2020-11-29 06:30

    Use this extension method: EntityExtensionMethods.cs

    public static void UpdateOnSubmit(this Table table, TEntity entity, TEntity original = null)
        where TEntity : class, new()
    {
        if (original == null)
        {
            // Create original object with only primary keys set
            original = new TEntity();
            var entityType = typeof(TEntity);
            var dataMembers = table.Context.Mapping.GetMetaType(entityType).DataMembers;
            foreach (var member in dataMembers.Where(m => m.IsPrimaryKey))
            {
                var propValue = entityType.GetProperty(member.Name).GetValue(entity, null);
                entityType.InvokeMember(member.Name, BindingFlags.SetProperty, Type.DefaultBinder,
                    original, new[] { propValue });
            }
        }
    
        // This will update all columns that are not set in 'original' object. For
        // this to work, entity has to have UpdateCheck=Never for all properties except
        // for primary keys. This will update the record without querying it first.
        table.Attach(entity, original);
    }
    

    To use it, make sure the entity object that you pass to UpdateOnSubmit method has all the primary key properties set for the record you want to update. This method will then update the record with the remaining properties from the entity object without pulling the record first.

    After calling UpdateOnSubmit, make sure to call SubmitChanges() for changes to apply.

提交回复
热议问题