Как я могу получить значение свойства от имени свойства в Linq до Sql? - PullRequest
1 голос
/ 20 октября 2010

У меня есть общий репозиторий.Для сохранения сущности в БД существует метод Save ().Я хочу проверить первичный ключ через Table.GetPropertyValue ("ID", сущность) - как мне это реализовать?

private Table<T> Table
{
    get { return db.GetTable<T>(); }
}

public void Save(T entity)
{
    if (Table.GetPropertyValue("ID", entity) == 0)
    {
         Add(entity);
    }
    else if (Table.GetOriginalEntityState(entity) == null)
    {
         Table.Attach(entity);
         Table.Context.Refresh(RefreshMode.KeepCurrentValues, entity);
    }
    db.SubmitChanges();
}

Ответы [ 3 ]

3 голосов
/ 20 октября 2010

Вы можете использовать динамический в C # 4:

if (((dynamic)entity).ID == 0)
    ....
2 голосов
/ 20 октября 2010

вы можете использовать отражение, но для этого случая использования я бы порекомендовал создать интерфейс:

public interface IHasId
{
    public int ID{get;}
}

заставить все соответствующие таблицы реализовать этот интерфейс (в частичном определении класса), затем вы можете попробоватьи бросьте entity в IHasId

1 голос
/ 20 октября 2010

Скажем, у меня есть класс B, определенный следующим образом:

public class B
{
    public int Id { get; set; }
}

Тогда вы можете получить значение идентификатора, как это:

var b = new B();
b.Id = 60;
int id = GetId(b);

с определенным методом GetIdследующим образом:

    public static int GetId(object o)
    {
        var idProperty = o.GetType().GetProperties().FirstOrDefault(p => p.Name == "Id");

        if (idProperty == null)
            throw new ArgumentException("object does not have an Id property", "o");

        if (idProperty.PropertyType.FullName != typeof(Int32).FullName)
            throw new ArgumentException("object has an Id property, but it is not of type Int32", "o");

        return (int)idProperty.GetValue(o, new object[] { });
    }

Более общим решением было бы создать метод, подобный этому:

    public static T GetProperty<T>(object o, string propertyName)
    {
        var theProperty = o.GetType().GetProperties().FirstOrDefault(p => p.Name == propertyName);

        if (theProperty == null)
            throw new ArgumentException("object does not have an " +  propertyName + " property", "o");

        if (theProperty.PropertyType.FullName != typeof(T).FullName)
            throw new ArgumentException("object has an Id property, but it is not of type " + typeof(T).FullName, "o");

        return (T)theProperty.GetValue(o, new object[] { });
    }

, который будет вызываться так:

var b = new B();
b.Id = 60;
int id = GetProperty<int>(b, "Id");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...