简体   繁体   中英

Get field by name in Entity Framework

What would be the easiest and least labour intensive (from the software POV) for me to be able to get a property (to be read and modified) from an entity generated via the Entity Framework?

Example (and simplified code) below:

// <auto-generated> from Entity Framework
public partial class tblCustomer
{
    public int CustomerID { get; set; }
    public string Status { get; set; }
}

For instance I would like:

tblCustomer customer = new tblCustomer();
int pCustomerID = customer.GetFieldByName("CustomerID");
pCustomerID = 100;

I've read a lot of answers about Reflection, but also comments that it's heavy processing (may be a bit excessive for my needs).

My example code may seem rather simplistic (so a solution would be rather pointless for that, the real code is based on large tables), but if there was some sort of GetFieldByName function I could reduce my code significantly as I have a lot of repetitious code doing the same stuff (just to different columns).

If I understand your problem correctly, I think you can use the changetracker for this (if the entity is in the context already).

dbContext.Entry(customer).CurrentValues["CustomerID"]

will give you the value of CustomerID for the customer object, provided it is attached to the dbContext instance.

If it is not part of the context, you can use Attach() to attach it first, or use Add() , if it's supposed to be a new record.

If you don't like to use Reflection the only way that i know is using a dictionary in your entities and also you can put all these stuff in a base class and your entities inherit it for example like that:

     [Serializable]
public class BaseEntity 
{
    Dictionary<string, object> _dic;

    public BaseEntity()
    {
        _dic = new Dictionary<string, object>();
    }

    public object this[string propertyName]
    {
        get
        {
            return _dic[propertyName];
        }
        set
        {
            _dic[propertyName] = value;
        }
    }      
}

public class tblCustomer : BaseEntity
{
    public int CustomerID
    {
        get
        {
            return (int)this["CustomerID"];
        }
        set
        {
            this["CustomerID"] = value;
        }
    }
    public string Status
    {
        get
        {
            return (string)this["Status"];
        }
        set
        {
            this["Status"] = value;
        }
    }
}

tblCustomer customer = new tblCustomer(); int pCustomerID = customer["CustomerID"];

and about performance cost of Reflection you can for first time store your memberInfos in a static field and use it for all instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM