开发者

LINQ: Create a subtable on an entity if not already there

I'm trying to create a method that can update the sub-table of an entity regardless of whether it's new or existing. My understanding is that for new entities, I add children like this:

ChildEntityENT child = new ChildEntityENT();
Entity.ChildEntityENT = child;

And from then on I can access it like this:

Entity.ChildEntityENT.Value1 = MyValue;
Entity.ChildEntityENT.Value2 = MyValue;

But I have a base class that I want to work with various Entity and ChildEntityENT types. My initial thought was to do something along these lines, but I can't seem to make it work. Basically I was going to let the developer use a lambda expression to point from the base Entity to the ChildEntityENT, and then my method would check the ChildEntityEnt and instantiate a new, blank copy if one didn't already exist. If it does exist, it doesn't need to do anything.

public void CreateIfNull(Expression<Func<Entity, object>> Child)
{
    if (Entity.Child == null)
    {
        ChildENT = new ChildENT();
        Entity.ChildENT = ChildENT;
    }
}

If I am totally missing the ball on this one, please let me know. I am all about finding easier ways to do things. I wish LINQ didn't require me to manually create a new ChildEntityENT before trying to assign values to it.

EDIT: I'm actually trying to do the开发者_运维问答 exact same thing as this guy: Adding a child entity to parent entityset


I ended up solving like this.

    public void CreateChildIfNull(LambdaExpression Child)
    {
        Type ChildType = Child.Body.Type;
        var NewChild = Activator.CreateInstance(ChildType);
        Entity.GetType().GetProperty(ChildType.Name).SetValue(Entity, NewChild, null);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜