Posterous theme by Cory Watilo

Filed under: LLBLGen

The Mystery of the Missing Permission

While writing Unit Tests for my membership provider code, I tried adding a permission I had defined on one test user to a different test user. I was completely freaked out, since user1 suddenly no longer had that permission.

What kind of witchery is this? Does Collection<T>.Add() remove items from the source collection?

No. It doesn't. I tried it all with simple collections. List<string>.Add() doesn't have this effect. So what's going on?

The problem has to be in my persistence layer. My User and Permissions objects are provided by LLBLGen. So it's gotta be something in there. (A light dawns). I look back at my table definitions. Sure enough, a permission as a m:1 relationship with it's user. A permission entity can't belong to more than one user. And LLBLGen is smart enough that when I take the object in the graph and add it to a different user, it not only updates the relationship(FK), but removes it from the original object.

But how do I get the result I wanted? A simple duplication of an existing permission? I adapted the deep copy method I found over on Stack Overflow into a general extension method and used it to dupe the permission as I added it. Clean copy in the object graph=>no changes to the relationship(FK)=>success.

public static class DeepCloneExtension { public static T DeepClone<T>(this T obj) { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T)formatter.Deserialize(ms); } } }