传递属性以在lambda表达式中使用

问题描述 投票:0回答:1

我在使用泛型方面遇到了麻烦。使用here中的示例,我想传递一个属性以便在EF Core中使用。我有一种感觉,我过度复杂的事情。请注意,我想坚持使用lamba表达式而不是传递像nameof这样的东西(我不能在4.0中使用它)。

class Foo
{
        public string A { get; set; } // some unique string in DbSet for entity Person
        public string B { get; set; } // some unique string in DbSet for entity Company

        public int GetId<TEntity>(string match, Expression<Func<TEntity, string>> fieldToExamine,  Expression<Func<TEntity, int>> fieldWithId, System.Data.Entity.DbContext context)
            where TEntity : class
        {
            int retval = -1;
            if (!string.IsNullOrEmpty(match))
            {
                var expr = (MemberExpression)fieldToExamine.Body;
                var prop = (PropertyInfo)expr.Member;
                var expr2 = (MemberExpression)fieldWithId.Body;
                var idField = (PropertyInfo)expr2.Member;
                // this works because everything is explicit
                var entity = context.Set<Person>().SingleOrDefault(p => p.PersonName.Equals(match));
                // ... but I want that to be generic
                // how to reference the property to be evaluated?
                //var entity = context.Set<TEntity>().SingleOrDefault(p => ...); // <- HELP?!
                if (entity != null)
                {
                    retval = (int)entity.GetType().GetProperty(idField.Name).GetValue(entity, null);
                }
            }
            return retval;
        }
}

static void Main(string[] args)
{
// .. omitted database stuff ..
// (for Person) what I want is to match the Name field (here: p.Name) of the Person entity to the Foo property value (here: f.A) and return the database id stored in p.PersonId
int x = f.GetId<Person>(f.A, p => p.PersonName, p => p.PersonId, context);
// same for Company, but different values and fields
int y = f.GetId<Company>(f.B, p => p.CompanyName, p => p.CompanyId, context);
}
c# entity-framework generics
1个回答
1
投票

Person类和Company类需要实现abstract classinterface

public abstract class BaseEntity
{
    public abstract int Id { get; set; }
    public abstract string Name { get; set; }
}

public class Person : BaseEntity
{
    public int PersonId { get; set; }
    public override string Name { get; set; }

    public override int Id
    {
        get { return PersonId; }
        set { PersonId = value; }
    }
}

public class Company : BaseEntity
{
    public int CompanyId { get; set; }
    public override string Name { get; set; }

    public override int Id
    {
        get { return CompanyId; }
        set { CompanyId = value; }
    }
}

然后你可以通过p.Namep.CompanyId

var entity = context.Set<TEntity>().SingleOrDefault(p => p.Name.Equals(match));
© www.soinside.com 2019 - 2024. All rights reserved.