开发者

Linq - How to put common fields in a base class

I 开发者_运维问答am trying to find a way so that I can push some common functionality into a base class for my Linq to SQL processing. I have two fields (ID and InsertUpdateOperID) that are common to most but not all of my tables. In my first go around I created a class called BaseEntity that had these fields. Unfortunately all I accomplished was hiding from the values in the .designer.cs file. I found an example of how to accomplish what I wanted In order to get around this (http://www.joe-stevens.com/2009/07/01/linq-to-sql-set-inheritance-modifiers-with-sqlmetal/). As per this article, I modifed the DBML file so that I could add the override modifier to the ID and InsertUpdateOperID properties on the tables that contained these two fields.

The net result of this was that the .designer.cs file added the override qualifier where I wanted it. This enabled me to create my BaseEntity class. Where I defined the ID field and the InsertUpdateOperID field as:

public virtual int ID                 { get; set; }  
public virtual int InsertUpdateOperID { get; set; } 

Doing this seemed to work fine.

The problem for me is that I hate the idea of modifying generated code. Can anyone suggest a way for me to put common fields and methods that act on those common fields in a base class so that I could accomplish what I want without modifying the generated .dbml?

Thanks


I'm facing the same problem today (wow, it's 1.5 years after your post), and struggled out a solution, so far it's good for me.

in the base class:

    public virtual int __ID
    { 
        get
        {
            PropertyInfo pi = this.GetType().GetProperty("ID");
            int id = (int)pi.GetValue(this, new object[] {});
            return id;
        }
        set
        {
            PropertyInfo pi = this.GetType().GetProperty("ID");
            pi.SetValue(this, value, new object[] { });
        }
    }

This looks quite voilent, but it works! Notice the __ before ID, because there is alread ID and _ID in the auto generated codes. As it's totally a new third way to access ID, no "override" is needed. And if you need, you can use the __ID in or via your base class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜