0

在我征服,试图程序的功能更强大的方式,我想出了下面的静态函数:确保给定输入(纯函数)的输出相同?

public static class BaseService 
{ 
    public static T EntityGet<T>(Guid id, XrmServiceContext xrmServiceContext) where T : Entity 
    { 
     return xrmServiceContext.CreateQuery<T>().Single(query => query.Id == id); 
    } 
} 

我们如何才能确保它是确定的,总是返回相同的值在规定输入?

请注意,XrmServiceContext是一个存储库,可能会根据连接是否打开或关闭而抛出。

我们是否应该将返回类型换成Maybe? :

public static Maybe<T> EntityGet<T>(Guid id, XrmServiceContext xrmServiceContext) where T : Entity 
{ 
    return xrmServiceContext.CreateQuery<T>().Single(query => query.Id == id).ToMaybe(); 
} 

这样我们可以100%确定返回值。

问题:也许变化后,可我们现在已经完全确定性的行为,无论仓库是在向上或向下?

+0

单个将抛出一个异常,如果数据库关闭,所以执行将不会达到ToMaybe。另外我不确定任何调用数据库的函数(外部存储)在严格意义上是否可以是纯粹的。 – Evk

+0

我不知道。我们可以得出结论:你不能有一个纯数据库调用的函数吗? –

回答

1

你可以把你的电话打个招呼,在最后,总是回复一个也许,但我不确定这是我会推荐的一个行动方案。这意味着每个正在检索实体的呼叫站点都必须处理检查可能,然后决定如果失败则应该怎么做。

在这种情况下,而不是追求“完美” enter image description here 我会接受错误发生,他们会泡。此外,由于您正在处理数据库,因此不能保证该值将存在于数据库中,或者它将保持相同的值(未更新)。

+0

hahhahhahhaha真棒图片 –

2

此代码xrmServiceContext.CreateQuery<T>().Single(query => query.Id == id).ToMaybe();存在问题,因为如果没有任何内容与查询匹配,IQueryable.Single将抛出InvalidOperationException

您需要在这里使用IQueryable.SingleOrDefault来避免异常并返回空值(假设您需要null)。您仍然需要将其封装在Try/Catch中以处理诸如数据库中断,超时等问题设置Try虽然便宜,但Catch可能很昂贵,所以我们希望避免将它用于逻辑。通过使用SingleOrDefault你处理最常见的例外,因为该ID不存在,并且允许如果希望使用写捕捉到只处理意料之外的(网络故障等)

public static T EntityGet<T>(Guid id, OrganizationServiceContext xrmServiceContext) where T : Entity 
{   
    try 
    { 
     return xrmServiceContext.CreateQuery<T>().SingleOrDefault(query => query.Id == id); 
    } 
    catch (Exception) 
    { 
     // Log the exception or this could create a debugging nightmare down the road!!! 
     return default(T); 
    }    
} 

Functional.Maybe库可以:

public static Maybe<T> EntityGet<T>(Guid id, OrganizationServiceContext xrmServiceContext) where T : Entity 
{ 
    try 
    { 
     return xrmServiceContext.CreateQuery<T>().SingleOrDefault(query => query.Id == id).ToMaybe(); 
    } 
    catch (Exception) 
    { 
     // Log the exception or this could create a debugging nightmare down the road!!! 
     return Maybe<T>.Nothing; 
    } 
} 
相关问题