4
특정 기본 유형의 엔티티가 포함 된 DbContext의 모든 DbSets를 반복하려고합니다. 내 목표는 내 DbContext에 SaveChanges를 호출하고 일부 기본 매개 변수를 설정하기 전에이 루프를 사용하는 것입니다. C#에서엔티티 프레임 워크 DbSet 리플렉션
, 내 기본 클래스는 다음과 같다 : -
public abstract class TrackedEntity
{
public string ModifiedBy { get; set; }
public DateTime Modified { get; set; }
}
파생 클래스의 예는 다음과 같습니다 -
public class Record : TrackedEntity
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
내 DbContext 클래스에서 사용자 지정 SaveChanges를 방법을 생성 한 TrackedEntity를 포함하는 각 DbSet에 대한 ProtertyInfo 목록을 가져올 수 있지만 각 DbSet의 값을 반복 할 때 DbSet에 파생 클래스의 내 DbSet (예 : DbSet < Record)을 전송할 수 없으므로 오류가 발생합니다. 기본 클래스 (예 : DbSet < T rackedEntity>).
public class MyContext : DbContext
{
public DbSet<Record> Records { get; set; }
public int SaveChanges(string username)
{
//Set TrackedEnity update columns
foreach (PropertyInfo property in GetDbSetPropertyInfos<TrackedEntity>())
{
foreach (TrackedEntity entity in (DbSet<TrackedEntity>)property.GetValue(this, null)) //fails here due to cast
{
entity.Modified = DateTime.UtcNow;
entity.ModifiedBy = username;
}
}
return base.SaveChanges();
}
//return a list of PropertyInfo for each DbSet with a given type in this context
IEnumerable<PropertyInfo> GetDbSetPropertyInfos<T>() where T : class
{
IEnumerable<PropertyInfo> properties = GetType().GetProperties().Where(p => p.PropertyType.IsGenericType
&& p.PropertyType.Name.StartsWith("DbSet")
&& p.PropertyType.GetGenericArguments().Length > 0
&& p.PropertyType.GetGenericArguments()[0].IsSubclassOf(typeof(T)));
return properties;
}
}
내가 달성하고자하는 것이 가능한지 아는 사람이 있습니까?
완벽한 덕분에! – user1573618