public class Book
{
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
public int Stock { get; set; }
public DateTime DateAdded { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
通过急切加载查询数据库时,如果其包含的嵌套类之一为null,则返回model null。我有一个图书实体,该实体具有两个从属类-作者和类别。我想标识为null的嵌套实体,并将其从查询中排除。如果它们都为null,则将它们都排除,并仅返回给定id的Book。我写出了以下lambda查询,但它看起来有点粗糙,对数据库的攻击次数太多,需要简化。有没有更好的方法可以使此逻辑看起来更加优雅和简化?
public ActionResult ProductView (int? id)
{
if (id != null)
{
var book = db.Books.Where(b => b.Id == id).Include(b => b.Author).Include(b=> b.Category.Books).SingleOrDefault();
if(book==null)
{
var bookWithCtg = db.Books.Where(b => b.Id == id).Include(b => b.Category).SingleOrDefault();
var bookWithAuth = db.Books.Where(b => b.Id == id).Include(b => b.Author).SingleOrDefault();
if (bookWithCtg == null&& bookWithAuth ==null)
book = db.Books.Where(b => b.Id == id).SingleOrDefault();
else if(bookWithAuth==null)
book = db.Books.Where(b => b.Id == id).Include(b => b.Category.Books).SingleOrDefault();
else if (bookWithCtg == null)
book = db.Books.Where(b => b.Id == id).Include(b => b.Author).SingleOrDefault();
}
book.DisplayNumber++;
db.SaveChanges();
return View(book);
}
else
return HttpNotFound();
}
答案 0 :(得分:0)
由于您的导航属性配置,在连接书籍,作者和类别时,EntityFramework使用内部连接。 如果一本书的作者和类别可以为空,则必须将AuthorId和CategoryId定义为 nullable int ,并按如下所示更改您的实体类型配置:
HasOptional(b => b.Author)
.WithMany(a => a.Books)
.HasForeignKey(b => b.AuthorId)
HasOptional(b => b.Category)
.WithMany(a => a.Books)
.HasForeignKey(b => b.CategoryId)
完成此配置后,您只需添加“作者”和“类别”即可。
var book = db.Books
.Where(b => b.Id == id)
.Include(b => b.Author)
.Include(b=> b.Category)
.SingleOrDefault();
现在,此查询将返回图书数据,无论作者和类别如何。