【发布时间】:2021-04-29 15:26:22
【问题描述】:
在我的模型中,我有 2 个类:ParticipantCompany 和 ParticipantPerson,它们都继承自 Participant 并具有字符串属性 .Name。他们也都意识到IParticipant 要求他们拥有.Name
public interface IParticipant
{
public string Name { get; set; }
}
public class ParticipantCompany : Participant, IParticipant
{
public ParticipantCompany():this(false, "","","","") { }
public ParticipantCompany (bool isclient) : this(isclient, "","","","") { }
public ParticipantCompany(bool isclient, string name, string address, string inncompany, string ogrn) : base(isclient, SubjectType.Company)
{
Name = name;
Address = address;
InnCompany = inncompany;
Ogrn = ogrn;
}
public string InnCompany { get; set; }
public string Ogrn { get; set; }
}
public class ParticipantPerson : Participant, IParticipant
{
public ParticipantPerson() : this(false,"","","","") { }
public ParticipantPerson(bool isclient) : this(isclient, "", "", "", "") { }
public ParticipantPerson(bool isclient, string name, string address, string innperson, string ogrnip) : base(isclient, SubjectType.Person)
{
Name = name;
Address = address;
InnPerson = innperson;
Ogrnip = ogrnip;
}
public string InnPerson { get; set; }
public string Ogrnip { get; set; }
}
public abstract class Participant
{
public Participant(bool isclient, SubjectType Type, string name, string address)
{
SubjType = Type;
IsClient = isclient;
Name = name;
Address = address;
}
public Participant(bool isclient, SubjectType Type ) : this(isclient, Type, "","")
{
}
public int Id { get; set; }
public SubjectType SubjType { get; private set; }
public bool IsClient { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<LegalCase> Cases { get; set; } = new List<LegalCase>();
}
这是模型本身:
class CaseContext : DbContext
{
public DbSet<ParticipantCompany> Companies{ get; set; }
public DbSet<ParticipantPerson> Persons { get; set; }
public DbSet<LegalCase> Cases { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=Clients.db");
}
我要做的是查询所有Companys 和所有Persons,将结果合并到一个列表中,然后按.Name 对列表进行排序。
using(var db = new CaseContext())
{
var companies = db.Companies.ToList();
var persons = db.Persons.ToList();
//Cant convert from System.Collections.
//Generic.List<Magna.CaseModel.ParticipantPerson> to
//System.Colleciton.Generic.IEnumerable<Magna.CaseModel.ParticipantCompany>
List<IParticipant> participants = companies.AddRange(persons);
}
【问题讨论】:
-
如果类型不同,你将无法做到这一点。也许像
companies.Cast<IParticipant>().Concat(persons.Cast<IParticipant>()).OrderBy(x => x.Name)这样的东西?但是,请注意您丢失了类型,并留下了IParticipant,但您没有提及这是否可以接受 -
我希望公司和个人在用户界面方面混合在一起(比如将他们的名字放在一个列表框上)我认为实际上将它们放入一个列表中并不是一个硬性要求,你会反对它吗?如果需要,我可以创建一个
List<string>的名称。 -
如果
participants会被 JSON 返回,那么我上面的评论可能就是你要找的,但 UI 是一个非常广泛的术语 -
您想将所有公司和个人放入什么的列表中?他们是两个不同的东西。它们可以转换为
Participant或IParticpant。您正在寻找的最终结果尚不清楚。 -
我的意思是在使用 WPF 创建的 GUI 中编辑数据库提供的数据
标签: c# list entity-framework-core-5