How to automate trimming strings in Entity Framework

When working with legacy data where the data being loaded into SQL server tables contains trailing spaces, the trailing spaces will remain in the fields regardless of whether the fields are varchar  This poses problems when doing compares or extracting data to files as you may not get the results you are looking for. One solution would be to add a trim to each field where this occurs.  This will result in having trims scattered all over your code base. Another and better solution would be to add an interception for Entity Framework that will trim all fields of certain data types. String Interceptor class As you can see, this will trim fields of types nvarchar, varchar, char, and nchar.  In the SQL generated, it will add a LTRIM and RTRIM to each field. To implement this interceptor, you just need to register it in a separate class within the same assembly. I found this solution based on Rowan Miller's EF6.1–Workaround Trailing Blanks Issue In String Joins … [Read more...]

NHibernate/DAO Unit testing

Unit Testing with using NHibernate and Data Access Objects [TestClass] public class AccountTest { private DATestHelper<CustomerDAO, CustomerDE> dh = new DATestHelper<CustomerDAO, CustomerDE>(); private DATestHelper<ProductDAO, ProductDE> dhProduct = new DATestHelper<ProductDAO, ProductDE>(); [TestInitialize()] public void TestInitialize() { dh.Init(); dhProduct.InitJoinSession(dh.session); } [TestCleanup()] public void TestCleanup() { dh.Cleanup(); dhProduct.CleanupJoinedSession(); } [TestMethod] public void GetAccountById() { CustomerDE c = dh.dao.FindById(1231); Assert.IsNotNull(c); } [TestMethod] public void GetProductByCode() { … [Read more...]

Entity Framework cloning

On a recent project, I had come across the need to copy an existing EF Entity.  Upon my research, I found several ways to accomplish this task.  One way is to create a new object and manually assign the property values using the existing object values.  You can also use some kind of mapping utility if it supports deep copying.  However, I will demonstrate two alternative ways to clone an Entity object using EF techniques. Disable EF Tracking When you are retrieving an entity or entities from a dataset, you can tell Entity Framework not to track any of the changes that you are making to that object and then add that entity as a new entity to the dataset.  With using .AsNoTracking, the context doesn't know anything about the existing entity. var entity = context.MyDataSet .AsNoTracking() .FirstOrDefault(e => e.Id == 1); context.MyDataSet.Add(entity); context.SaveChanges(); You can also include child entities as well var entity = … [Read more...]