开发者

"Adding a child row to parent's child collection" v.s. "adding a child to datacontext's child collection"

"Adding a child row to parent's child collection" v.s. "adding a child to datacontext's child collection"

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 overri开发者_如何学Goden 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?


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:

Rsvp r = new Rsvp();
r.AttendeeName = "xport";
r.DinnerId = 10000; // this throws a compiler error. good! we do not want people tinkering with FK's.
Dinner d = entities.Dinners.First(x => x.DinnerId == 1);
d.Rsvps.Add(r); // this is the correct way to add a RSVP
entities.SaveChanges(); 

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜