[英]Is there a more elegant way to specify multiple one to many relations of same nature?
I'm having trouble trying to create the following entities relations.我在尝试创建以下实体关系时遇到问题。 My code has the classes
Shop
and Person
, and both have multiple Phones
.我的代码有
Shop
和Person
类,并且都有多个Phones
。 My first implementation was something like this:我的第一个实现是这样的:
public class Person {
public int Id;
public string Name;
public virtual ICollection<Phone> Phones;
}
public class Shop {
public int Id;
public string Name;
public virtual ICollection<Phone> Phones;
}
public class Phone {
public int Id;
public string AreaCode;
public string Number;
public int? ShopId;
public virtual Shop Shop;
public int? PersonId;
public virtual Person Person;
}
and the model builder like和模型构建器一样
modelBuilder.Entity<Person>()
.HasMany(p => p.Phones)
.WithOptional(p => p.Person)
.HasForeignKey(p => p.PersonId);
modelBuilder.Entity<Shop>()
.HasMany(p => p.Phones)
.WithOptional(p => p.Shop)
.HasForeignKey(p => p.ShopId);
My doubt here is: can I model it or change anything in my classes so when I'm handling the phones I don't have to keep checking if they are related to a Shop
or a Person
?我的疑问是:我可以建模或更改我的课程中的任何内容,以便在我处理电话时我不必继续检查它们是否与
Shop
或Person
?
I would suggest the next scheme:我建议下一个方案:
public class Owner
{
public int Id;
public string Name;
public virtual ICollection<Phone> Phones;
public abstract SendMessage(Phone phone);
}
public class Person : Owner
{
public override SendMessage(Phone phone)
{
...
}
}
public class Shop : Owner
{
public override SendMessage(Phone phone)
{
...
}
}
public class Phone {
public int Id;
public string AreaCode;
public string Number;
public int? OwnerId;
public virtual Owner Owner;
}
So you haven't two entities with duplicating fields and, as npinti mentioned, you delegate messaging function to the corresponding entity.因此,您没有两个具有重复字段的实体,并且正如 npinti 所提到的,您将消息传递功能委托给相应的实体。
To add a little bit more context to my comment, the way I would go about it (with the information currently at hand) would be as follows:为了在我的评论中添加更多上下文,我将采取的方式(使用当前手头的信息)如下:
IMessageSender
, which has 1 method: SendMessage(Phone destination)
.IMessageSender
,它有 1 个方法: SendMessage(Phone destination)
。Shop
and Person
class implement that interface.Shop
和Person
类实现该接口。 In the implementation of the method you would then have your logic which, from the comments, should differ from Person
and Shop
.Person
和Shop
不同。SendMessage
.SendMessage
。 This will, in turn, delegate the logic of the construction of the message to the appropriate class.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.