开发者

Map Domain Entity Properties to Word Bookmarks

开发者 https://www.devze.com 2023-03-24 18:57 出处:网络
We need to print Word documents that have bookmarks in them. We also have domain entities whose properties map to one (or more) of the bookmarks in the Word documents. Right now, to test, we have a sw

We need to print Word documents that have bookmarks in them. We also have domain entities whose properties map to one (or more) of the bookmarks in the Word documents. Right now, to test, we have a switch statement (foo is the domain entity):

    private static string GetValueForBookmark(Bookmark bookmark, Foo foo)
    {
        // ToDo: Un-switch this.

        switch (bookmark.Name)
        {
            case "dist":
                return foo.Measurment.Distance;
            case "serialNo":
                return foo.SerialNumber;
            default:
                return string.Empty;
        }
    }

I would hate to add attributes to the properties of Foo in the framework. It seems messy and wrong, since the domain entities shouldn't know about all these one-off application needs.

One idea is to create a mapping of bookmark names to domain entity properties. Maybe create an enum that represents the bookmark names, then add attributes to these enum elements, that represent domain entity properties. The attributes would have to specify these properties, and I don't know if that can be done. Can expression trees be used here?

Is there another option? I simply want to map domain entity properties to string literals.

What is the best way to solve t开发者_如何学编程his?


I just went with this:

    private static void MapBookmarksToFooProperties()
    {
        if (_bookmarkToFooPropertyMapping != null) { return; }  // We already created the mapping.

        _bookmarkToFooPropertyMapping = new Dictionary<string, Func<Foo, string>>();

        // Associate Word document bookmarks to their properties within a Foo object.

        _bookmarkToFooPropertyMapping.Add("dist", foo => foo.Measurment.Distance);
        _bookmarkToFooPropertyMapping.Add("serialNo", foo => foo.SerialNumber);
        // More mapping here
    }     

Then, accessing it, is as simple as this:

return _bookmarkToFooPropertyMapping[bookmark.Name](foo);
0

精彩评论

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

关注公众号