我有以下问题:
我有一个(简化的)实体,它是这样的自引用:
public class User
{
public string Username { get; set; }
public string Password { get; set; }
public string ModifiedById {get; set; }
public User ModifiedBy { get; set; }
}
...使用以下FluentAPI:
modelBuilder.Entity<User>().
HasKey( k => k.Username );
modelBuilder.Entity<User>().
HasOptional( x => x.ModifiedBy ).
WithMany().
HasForeignKey( x => x.ModifiedById );
......它有效。然后我有一个方法来获取任何实体的主键:
public IEnumerable<EdmMember> GetPrimaryKeys( DbContext Db, DbEntityEntry Entry )
ObjectContext objectContext = ( (IObjectContextAdapter)Db ).ObjectContext;
MethodInfo methodInfo = objectContext.GetType().GetMethod("CreateObjectSet", new Type[] { } );
methodInfo = methodInfo.MakeGenericMethod( Entry.Entity.GetType() );
object objectSet = methodInfo.Invoke(objectContext, null); // null in combination with self referencing entity
PropertyInfo propertyInfo = objectSet.GetType().GetProperty("EntitySet");
EntitySet entitySet = (EntitySet) propertyInfo.GetValue(objectSet, null);
return entitySet.ElementType.KeyMembers;
}
每个单独为我工作,但当我尝试获取自引用实体的主键时,我收到错误,因为objectSet
变为null
。
有人可以帮忙吗?