如何从Linq中的属性名称获取属性值到Sql?

时间:2010-10-20 14:38:41

标签: linq-to-sql

我有通用存储库。 Save()方法可以在db中持久保存实体。我想通过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 个答案:

答案 0 :(得分:3)

您可以在C#4中使用动态:

if (((dynamic)entity).ID == 0)
    ....

答案 1 :(得分:2)

你可以使用反射,但对于这个用例,我建议创建一个界面:

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

使所有相关表实现此接口(在部分类定义中),然后您可以尝试将entity转换为IHasId

答案 2 :(得分:1)

说我的B类定义如下:

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

然后你可以像这样得到id的值:

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");