我试图得到一个m2m / one2many关系中的类型,例如,我有两个模型Student和Course。
学生模型:
public class Student
{
public int Id { get; set;}
public string Name { get; set;}
public ICollection<Course> CompletedCourses { get; set;}
public ICollection<Course> FavoriteCourses { get; set;}
public ICollection<Course> CreateCourses { get; set;}
}
课程模型
public class Course
{
public int Id { get; set;}
public string Name { get; set;}
public int CreateStudentId {get; set;}
public virtual Student { get; set;}
public ICollection<Student> Students { get; set;}
public ICollection<Student> FavoriteByStudents { get; set;}
}
现在假设我使用来自两个实体的反射得到两种类型,并且我想检查它们是否处于m2m / one2may关系中。我使用了这段代码,如果两种类型处于m2m关系中,则返回true,但我无法指定属性名称,因为在某些情况下,两种类型与同一类型具有多个关系。 这是我的代码试图从MetadataWorkspace获取两种类型的m2m关系:
private bool IsInManyToManyRelaship(Type type1, Type type2, string navigationPropertyName)
{
var metadata = ((IObjectContextAdapter)DbContext).ObjectContext.MetadataWorkspace;
var all_ssociations = metadata.GetItems<AssociationType>(DataSpace.CSpace);
var m2m_ssociations = all_ssociations.Where(x => x.RelationshipEndMembers.Any(r => r.RelationshipMultiplicity == RelationshipMultiplicity.Many));
return m2m_ssociations.Any(x => (x.RelationshipEndMembers[0].GetEntityType().Name == type1.Name && x.RelationshipEndMembers[1].GetEntityType().Name == type2.Name )
|| (x.RelationshipEndMembers[1].GetEntityType().Name == type1.Name && x.RelationshipEndMembers[0].GetEntityType().Name== type2.Name));
}