【发布时间】:2021-02-13 10:30:23
【问题描述】:
在使用通用存储库模式时,我有以下用于添加实体的功能:
public class BaseRepository<TEntity> : IBaseRepository<TEntity>
where TEntity : class, IEntity
{
public async Task<TEntity> AddEntity(TEntity entity)
{
this.databaseContext.Set<TEntity>().Add(entity);
await this.databaseContext.SaveChangesAsync();
return entity;
}
}
我有两个实体,公司和用户之间存在一对多的关系:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
我从我的控制器收到具有以下属性的用户模型:
{
string Name = "Example User",
int[] Companies = [1, 3, 7] <--- representing existing company-id's
}
我现在能否以某种通用方式从int[] Companies 转到填充的List<Company> Companies (因为我有多个这样的实体)?
可能是这样的:
- 从“TEntity”中获取所有“导航属性名称”,这将导致“公司”。
- 然后,在控制器模型中找到匹配的属性,这将导致
int[] Companies。 - 然后,根据匹配的
int[] Companies中的ID 填充List<Company> Companies。 - 最后,保存 TEntity。
这样的事情能实现吗?
【问题讨论】:
标签: c# generics entity-framework-core