c# - 如果数据库中没有这样的行,我将返回什么?

标签 c# entity-framework error-handling

我使用的是Entity Framework,并且我有一个Repository类,该类可以使用dbContext对象获取所有数据。

目前有一种方法叫做

public MovieDetails FindSingle(int? id)
{
    using (MovieContext dbContext = new MovieContext())
    {
        var newMovieDetails = dbContext.Movies.FirstOrDefault(x => x.MovieID == id);
        if (newMovieDetails == null)
        {
            throw new Exception();
        }
        var MappedDetails = new MovieDetails
        {
            MovieID = newMovieDetails.MovieID,
            MovieName = newMovieDetails.MovieName
        };
        return MappedDetails;
    }
}

当前,当程序在数据库中找到匹配项时,它将转换为Data Object Transfer-object。当我尝试搜索数据库中不存在的电影时,出现错误。有没有办法我可以返回一个类型,表明数据库中不存在这样的行?还是我应该只返回一个空对象?

最佳答案

对这样的东西使用异常是一个坏主意。
异常是特殊情况,即您无法在代码中控制的事情,例如网络错误和I/O权限冲突。
这种事情就是Eric Lippert would call a vexing exception:

Vexing exceptions are the result of unfortunate design decisions. Vexing exceptions are thrown in a completely non-exceptional circumstance, and therefore must be caught and handled all the time.

The classic example of a vexing exception is Int32.Parse, which throws if you give it a string that cannot be parsed as an integer. But the 99% use case for this method is transforming strings input by the user, which could be any old thing, and therefore it is in no way exceptional for the parse to fail. Worse, there is no way for the caller to determine ahead of time whether their argument is bad without implementing the entire method themselves, in which case they wouldn't need to be calling it in the first place.

This unfortunate design decision was so vexing that of course the frameworks team implemented TryParse shortly thereafter which does the right thing.


如果MappedDetails是引用类型,则最好返回null(如果找不到)。
如果是值类型,请更改方法以返回MovieDetails?并返回null
我还建议将您的方法名称从FindSingle更改为GetMovieDetails或类似的内容。
这样,当您查看6个月后的代码时,会看到类似以下内容的代码:
....
var details = GetMovieDetails(id);
....
您可以立即了解该方法的实际作用,
....
var details = FindSingle(id);
....
基本上什么都不会告诉你。

关于c# - 如果数据库中没有这样的行,我将返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50384654/

相关文章:

php - 可过滤的侧边栏已替换为错误消息

c# - 在 Python 中获取 C# 日志

c# - 网络核心 : Code Generation for IEquatable/Equals for Comparing Two Class Models

winforms - 如何将 Entity Framework 关联绑定(bind)到 ComboBox?

python - Python输入 “-”

python - Python 有 argc 参数吗?

c# - 不确定在哪里问,哪个 1 实际上更好?

c# - 如何从 Visual Studio 2017 将现有解决方案添加到 GitHub?

c# - 如何在不选择新模型的情况下包含导航属性?

SQL Azure 联合和原子单元标识