实体框架和与1:0..n关系的关系,当它为0时该怎么办?

时间:2015-02-20 19:45:29

标签: c# null navigation associations entity-framework-4.1

在我支持的应用程序中,有时关联可以为null,因为客户端尚未提交数据。除了进行空检查之外,我不知道有任何其他方法来处理这个问题。数据库是一成不变的(其他应用程序也使用它)它将我的代码变成一团糟。我想知道是否有更好的方法来执行此操作(此代码将进入匿名类型,但使用类没有区别。我无法添加谓词检查null,因为如果该帐单存在该信息无论索赔患者或索赔是否存在,都需要退回。以下是简化版本:

            var baseQuery = Context.Bills.AsNoTracking()
            .Select
            (
                bill => new
                {
                    bill.BillId,
                    bill.BillStatus,
                    patientId = bill.ClaimPatient != null ? bill.ClaimPatientId : null,
                    claimPatientId =  bill.ClaimPatient != null && bill.ClaimPatient.Claim != null ? bill.ClaimPatientId : null,
                    bill.UserNumber,
                }
            );

这种空检查可以继续进行。我知道可能有更好的方法,当我看到它时,我将面对植物,因为它可能是一个如此简单和明显的东西,我错过了。

2 个答案:

答案 0 :(得分:1)

我发现以下扩展方法有时对处理此问题很有用。

public static class Extensions
{
    public static U Maybe<T, U>(this T t, Func<U> f) where U : class
    {
        return t != null ? f() : null;
    }

    public static U Maybe<T, U>(this T t, Func<T, U> f) where U : class
    {
        return t != null ? f(t) : null;
    }

    public static U? MaybeNullable<T, U>(this T t, Func<U> f) where U : struct
    {
        return t != null ? f() : (U?)null;
    }

    public static U? MaybeNullable<T, U>(this T t, Func<T, U> f) where U : struct
    {
        return t != null ? f(t) : (U?)null;
    }
}

以下是一些示例用法。

bill.ClaimPatient.Maybe(() => bill.ClaimPatientId)
bill.ClaimPatient.Maybe(cp => cp.Id)

person.Maybe(p => p.Employer).Maybe(e => e.Address)

答案 1 :(得分:1)

好消息:SQL没有这个null参考概念。因此,您可以将检查(在本例中)简化为int?

var baseQuery = Context.Bills.AsNoTracking()
.Select
(
    bill => new
    {
        bill.BillId,
        bill.BillStatus,
        patientId = (int?)bill.ClaimPatientId,
        claimPatientId = (int?)bill.ClaimPatientId,
        ClaimPatient.UserNumber,
    }
);

整个语句被翻译成SQL。 CLR知道的第一件事是来自数据库的结果集。此集可能包含空值,因此您只需确保最终结果可以在一个属性中包含intnull

也许你需要第二个Id值bill.ClaimPatient.Claim != null ? bill.ClaimPatientId : null,但我认为是业务逻辑,而不是空的安全检查。