How to automate setting ConcurrencyMode=Fixed on all RowVersion columns?

前端 未结 7 1392
攒了一身酷
攒了一身酷 2021-01-04 13:03

EF defaults to no concurrency control (last write wins) which allows lost updates. Enforcing optimistic concurrency checks can explicitly be configured by setting Concurrenc

相关标签:
7条回答
  • 2021-01-04 13:30

    This is similar to the answer by Mohamed Cassim, but I've updated the code to use XML attribute search and replace, instead of string replace, as the designer can change the order of attributes, or other properties can have different values.

    Save this as FixVersionColumnConcurrencyMode.cs, run csc FixVersionColumnConcurrencyMode.cs, and run the resulting FixVersionColumnConcurrencyMode.exe in the same folder as the .edmx file. You can also make it execute post build of the project.

    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Xml.Linq;
    
    namespace Utility
    {
        internal class FixVersionColumnConcurrencyMode
        {
            private static void Main(string[] args)
            {
                string directoryPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var files = Directory.GetFiles(directoryPath, "*.edmx");
                foreach (var file in files)
                {
                    XDocument xmlDoc = XDocument.Load(file);
    
                    IEnumerable<XElement> versionColumns =
                        from el in xmlDoc.Descendants()
                        where (string)el.Attribute("Name") == "Version"
                        && (string)el.Attribute("Type") == "Binary"
                        && (string)el.Attribute("ConcurrencyMode") != "Fixed"
                        select el;
                    bool modified = false;
                    foreach (XElement el in versionColumns)
                    {
                        modified = true;
                        el.SetAttributeValue("ConcurrencyMode", "Fixed");
                    }
                    if (modified)
                        xmlDoc.Save(file);
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题