ASP.NET Core MVC:赋值Blog.Name到ViewData遇对象引用错误求助
问题描述
我尝试获取Blog模型中的Name字段,该字段定义如下:
public string Name { get; set; }
控制器Index方法中的相关代码:
var posts = await _context.Posts .Where(p => p.BlogId == id && p.ReadyStatus == ReadyStatus.ProductionReady) .Include(p => p.Blog) .OrderByDescending(b => b.Created) .ToPagedListAsync(pageNumber, pageSize); ViewData["BlogName"] = Blog.Name;
执行时最后一行出现错误:
An object reference is required for the non-static field, method or property for "Blog.Name"
错误原因
Blog.Name是直接访问类的非静态成员,但Name是实例属性,必须通过Blog类的具体对象(实例)才能访问,不能直接用类名调用。
解决方案
根据业务场景,有两种常见处理方式:
方式1:从查询到的Posts集合中获取关联Blog实例
因为代码中通过p.BlogId == id过滤,所有查询到的Post都属于同一个Blog,可直接取第一个Post关联的Blog对象:
var posts = await _context.Posts .Where(p => p.BlogId == id && p.ReadyStatus == ReadyStatus.ProductionReady) .Include(p => p.Blog) .OrderByDescending(b => b.Created) .ToPagedListAsync(pageNumber, pageSize); // 从第一个Post中获取Blog名称,同时处理空集合情况 ViewData["BlogName"] = posts.Any() ? posts.First().Blog.Name : string.Empty;
方式2:直接查询指定ID的Blog记录
如果不需要依赖Posts集合,可直接从数据库查询目标Blog:
// 先查询对应ID的Blog var blog = await _context.Blogs.FindAsync(id); // 处理Blog不存在的情况,避免空引用异常 ViewData["BlogName"] = blog?.Name ?? string.Empty; // 再执行Posts查询逻辑 var posts = await _context.Posts .Where(p => p.BlogId == id && p.ReadyStatus == ReadyStatus.ProductionReady) .Include(p => p.Blog) .OrderByDescending(b => b.Created) .ToPagedListAsync(pageNumber, pageSize);
注意事项
- 使用
?.和??运算符可以避免对象为null时的空引用异常,提升代码健壮性 - 如果业务逻辑能确保
id对应的Blog一定存在,可简化为空值判断,但建议保留异常处理逻辑
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

