Class design: entity ID vs entity reference

陌路散爱 提交于 2019-12-11 12:59:16

问题


If I've got Foo with a property of type Bar. Both are persisted in a database which can be retrieved by an ID. (The IDs are actually used in the line of business by customer service claims. So they're not just index placeholders.) I could take the approach shown with b1 or b2.

Chaining entities together scares me since if you push that too far, it's easy to get Null's popping up. On the other hand, having the ID show up everywhere seems like it's adding unnecessary wordiness.

int fooKey = 123;
Foo f = new Foo(fooKey);
Bar b1 = new Bar(Foo.BarID);  //This?
Bar b2 = Foo.Bar;  // Or This?

Note: This is NOT about the .NET Entity framework. The word entity is used here in the general sense.


回答1:


As a general rule I try to avoid chaining, because it usually introduces unncessary tight coupling. All depends on the context, but in terms of business objects it might be a good idea to keep the entities loosely coupled so they can grow independently.

In the example you provide I don't think tight coupling is warranted. If the intersection was greater this might be warranted, but this isn't the general case with Business entities, I've found.




回答2:


Take a look at the way MSFT implemented LINQ to SQL. They let you set either/or. Their mapper is smart enough to expose both properties and lazy-load as necessary. IMO you should go the simplest way (use an ID) or use an O/R mapper like Hibernate/NHibernate, Linq to SQL, or Linq to Entities if you want fanciness.



来源:https://stackoverflow.com/questions/505305/class-design-entity-id-vs-entity-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!