简体   繁体   English

处理具有潜在空子类的复杂类的良好设计模式是什么?

[英]What is a good design pattern for dealing with complex classes that have potential null sub classes?

I am using Entity Framework Model First to create a data access layer. 我正在使用Entity Framework Model First创建数据访问层。 In my MVC project I am using this DAL to retrieve a complex object from my DB. 在我的MVC项目中,我正在使用此DAL从数据库中检索复杂的对象。

var street2 = Person.Address.Street2;

What I am trying to determine is what pattern or process I should be using to handle potential situations where Street2 or even Address doesn't have a record in the DB. 我要确定的是应该使用哪种模式或流程来处理Street2甚至Address在数据库中没有记录的潜在情况。

I know I could test for null objects at the point where I am using them but I was wondering if there is a pattern or method that would remove the need to do that at such a fine grained level. 我知道我可以在使用空对象的时候对其进行测试,但是我想知道是否有某种模式或方法可以消除在如此细粒度的级别上进行操作的需要。 ie

if(Person.Address!=null && Person.Address.Street2!=null)
{
var street2 = Person.Address.Street2;
}

Until we get a Safe Navigation Operator is there another good pattern to use? 在获得安全导航操作员之前 ,还有其他好模式可以使用吗?

Would it make sense to create a getter in the classes to check for null objects and if there is create a new empty object and return that? 在类中创建一个getter来检查空对象是否有意义,是否存在创建一个新的空对象并返回该空对象?

Am I making this more complex then it needs to be? 我要使它变得更复杂吗?

Any thoughts on AutoMapper and it's null substitution? 关于AutoMapper的任何想法,它是null替代吗?

No. That's the way you've to do it. 不,这就是您要做的方式。 You've to do it the way you're doing. 您必须按照自己的方式去做。

However use short circuit in your if conditions to increase performance 但是,在if情况下使用短路以提高性能

您可以创建对象验证器并使用Decorator模式进行更新,这样,您仍然必须手动在逻辑需要的地方检查是否为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM