Best Practices for Managing Linq to SQL Dbml Files?

前端 未结 5 771
囚心锁ツ
囚心锁ツ 2020-12-04 15:44

I\'ve just started using Linq to SQL, and I\'m wondering if anyone has any best practices they can share for managing dbml files.

  • How do you keep them up to da
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 16:30

    Since you asked for other tips and tricks for managing DBML...

    When DBML files are refreshed from the database, there are certain schema settings which they don't pick up on, such as default column values, forcing you to manually change the setting. This can lead to lost hours every time you refresh the DBML without realizing or remembering where you need to make manual adjustments, and your code starts failing.

    To guard against this, one trick is to write a unit test which uses reflection to check the LINQ metadata for those (manual) settings. If the test fails, it gives a descriptive error message, instructing the user to make the proper change to the column properties. It's not a perfect solution, and it might not be convenient if you have many manual settings, but it can help avoid some major pain for yourself and your team.

    Here's an example of an nunit test to check that a column is set to auto-generate from the DB.

        [Test]
        public void TestMetaData()
        {
            MyObj my_obj = new MyObj()
            {
                Foo = "bar",
            };
    
            Type type = MyObj.GetType();
            PropertyInfo prop = type.GetProperty("UpdatedOn");
            IEnumerable info = (IEnumerable)prop.GetCustomAttributes(typeof(ColumnAttribute), true);
            Assert.IsTrue(
                info.Any(x => x.IsDbGenerated == true), 
                "The DBML file needs to have MyObj.UpdatedOn AutoGenerated == true set. This must be done manually if the DBML for this table gets refreshed from the database."
            );
        }
    

提交回复
热议问题