“将子行添加到父级的子集合中” vs “将子项添加到 datacontext 的子集合中”
我将比较 2 个场景来添加 Rsvp 行。在制作过程中您更喜欢哪一种?
方法 1:将新的 Rsvp 对象添加到 datacontext 的 Rsvp 集合
Rsvp r = new Rsvp();
r.AttendeeName = "xport";
r.DinnerId = 1;//there will be an exception if it is set to a Dinnner object that does not exist.
entities.Rsvps.AddObject(r);
entities.SaveChanges();
如果我们尝试将dinnerId设置为不存在的Dinner对象,我们将得到一个异常。这种行为是一致且直接的。
方法 2:将新的 Rsvp 对象添加到晚餐对象的 Rsvps 属性
Rsvp r = new Rsvp();
r.AttendeeName = "xport";
r.DinnerId = 10000;//this Dinner does not exist!
Dinner d = entities.Dinners.First(x => x.DinnerId == 1);
d.Rsvps.Add(r);
entities.SaveChanges();
Rsvp 对象的外键属性 DiningId 可以设置为任意数字。当将此 Rsvp 对象添加到 Dining 对象的 Rsvps 集合中时,DinnerId 将被静默覆盖。上面的示例显示晚餐 ID 设置为 10000,这是不存在的晚餐对象的 ID。这是不可避免的行为吗?
I will compare 2 scenarios to add Rsvp rows. Which one do you prefer in production?
METHOD 1: Adding a new Rsvp object to datacontext's Rsvp collection
Rsvp r = new Rsvp();
r.AttendeeName = "xport";
r.DinnerId = 1;//there will be an exception if it is set to a Dinnner object that does not exist.
entities.Rsvps.AddObject(r);
entities.SaveChanges();
We will get an exception if we attempt to set DinnerId to a Dinner object that does not exist. This behavior is consistent and straightforward.
METHOD 2: Adding a new Rsvp object to a Dinner object's Rsvps properties
Rsvp r = new Rsvp();
r.AttendeeName = "xport";
r.DinnerId = 10000;//this Dinner does not exist!
Dinner d = entities.Dinners.First(x => x.DinnerId == 1);
d.Rsvps.Add(r);
entities.SaveChanges();
The foreign key property DinnerId of a Rsvp object can be set to any number. When this Rsvp object is added to a Dinner object's Rsvps collection, the DinnerId will be overriden silently. Example above shows DinnerId is set to 10000 which is an Id of an Dinner object that does not exist. Is it an unavoidable behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
肯定是方法2。
为什么?因为如果没有晚餐,Rsvp 就不可能存在。在这种关系中,Dinner 是父级 - 如果我们要创建一个存储库,我们将创建一个 DinnerRepository (因为 Dining 是 DDD 术语中的“聚合根”)
关于您的注释 - 是的,这是可以避免的行为 - 您应该做的是不要公开模型上的外键。这是创建/更新模型时可用的选项。
这样,关系必须通过实体创建/修改:
换句话说 - 创建/修改 Rsvp 的唯一方法是通过晚餐 - 并且 FK 属性无法修改。
这是有道理的。
Definetely method 2.
Why? Because a Rsvp cannot exist without a Dinner. In this relationship, Dinner is the parent - and if we were to create a Repository, we would create a DinnerRepository (as Dinner is the "aggregate root" in DDD terms)
In regards to your note - yes, this is avoidable behaviour - what you should do is don't expose the foreign keys on the model. This is an option available when you create/update your model.
This way, the relationships must be created/modified via the entity:
In other words - the only way to create/modify a Rsvp is via a Dinner - and the FK property cannot be modified.
Which makes sense.