在查看 GitHub 中的源代码后,我可以有足够的信心说 EF Core 中不存在 Multiplicity 这样的东西。
我创建了一个枚举,就像使用的 .net Framework 3.5+ 一样(参见:官方文档):
public enum RelationshipMultiplicity
{
Many = 2,
One = 1,
ZeroOrOne = 0
}
然后是一个扩展方法,它允许使用枚举作为过滤器获取所有导航属性。我使用的关键是:
该方法允许按关系类型获取所有导航属性
public static class ModelExtensions
{
/// <summary>
/// Extension method used to get from the entity all navigation properties by multiplicity
/// </summary>
/// <typeparam name="T">Entity from where the navigation properties are taken</typeparam>
/// <param name="model">Context Model</param>
/// <param name="multiplicity">Type of multiplicity to use</param>
/// <returns>List of PropertyInfo of Navigation Properties</returns>
public static IEnumerable<PropertyInfo> GetNavigationProperties<T>(this IModel model, RelationshipMultiplicity multiplicity)
{
var navigations = model.GetEntityTypes().FirstOrDefault(m => m.ClrType == typeof(T))?.GetNavigations();
var properties = new List<PropertyInfo>();
switch (multiplicity)
{
case RelationshipMultiplicity.Many | RelationshipMultiplicity.ZeroOrOne:
return navigations?
.Select(nav => nav.PropertyInfo);
case RelationshipMultiplicity.Many:
return navigations?
.Where(nav => nav.IsCollection())
.Select(nav => nav.PropertyInfo);
case RelationshipMultiplicity.One:
return navigations?
.Where(nav => !nav.IsCollection() && nav.ForeignKey.IsRequired)
.Select(nav => nav.PropertyInfo);
case RelationshipMultiplicity.ZeroOrOne:
return navigations?
.Where(nav => !nav.IsCollection())
.Select(nav => nav.PropertyInfo);
default:
return null;
}
return properties;
}
}
使用示例:
var oneToManyRelations = _context.Model.GetNavigationProperties<Transaction>(
RelationshipMultiplicity.ZeroOrOne);
var manyToOneRelations = _context.Model.GetNavigationProperties<Transaction>(
RelationshipMultiplicity.Many);
var allRelations = _context.Model.GetNavigationProperties<Transaction>(
RelationshipMultiplicity.Many |
RelationshipMultiplicity.ZeroOrOne);