如何在实体框架中向导航属性插入值 [英] How do I insert value to navigation property in entity framework

查看:67
本文介绍了如何在实体框架中向导航属性插入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:



  public   class 预订
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public < span class =code-keyword> int BookID { get ; set ; }

public string bookName {获得; set ; }
public string bookAuthor { get ; set ; }

public string bookTranslator {获得; set ; }

public DateTime registerDate { get ; set ; }


public virtual ICollection< Category>类别{获取; set ; }
}

public class 类别
{

public int CategoryId {获得; set ; }

[StringLength( 50 )]
public string categoryName { get ; set ; }

[DataType(DataType.Text)]
public string categoryDe​​scription { get ; set ; }

public virtual ICollection< Book>图书{获取; set ; }
}





现在我想在我的书中添加类别
控制器中的
: br />

  int  catID =  int  .Parse( form [  ddlCat]); 
IEnumerable< Category> _cats = db.Categories.Where(x = > x.CategoryId == catID);
book.Category.Add(_cats.FirstOrDefault());
db.Books.Add(书);
db.SaveChanges();





并且在视图中:



< div  =  表单-group >  
< label class = control-label col-md-2 for = DepartmentID> Cats < / 标签 >
< div class = col-md-10 >
@ Html.DropDownList( ddlCat new SelectList(ViewBag.Category,< span class =code-string> Value Text))
@ Html.ValidationMessageFor(model = > model.Category)
< span class =code-keyword>< / div >
< / div >





我的尝试:



i尝试添加用户选择的类别,但它在下面的行中给我错误



 book.Category.Add(_cats.FirstOrDefault()) ; 





对象引用未设置为对象的实例。

解决方案

< blockquote>调试器可能会给你一些关于发生了什么的提示。要获得该类别,您必须在IQueryable上运行FirstOrDefault。您的代码所做的是立即将查询的返回视为IEnumerable。如果查询没有返回任何行,则IEnumerable将为null。由于您无法在null上调用方法或属性,因此会收到您收到的异常消息。

  //  从表单中获取类别ID  
int catID = int .Parse(form [ ddlCat]);

// 从数据库中获取Category对象
< span class =code-keyword> var category = db.Categories.Where(x = > x.CategoryId == catID).FirstOrDefault( );

// 我们是否收到了Category对象?
if (category!= null
{
// 将类别添加到图书类别集合
book.Category.Add(category);
}

// 将书籍添加到数据库中的Books表
db.Books.Add(book);
db.SaveChanges();


i have below model:

public class Book
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int BookID { get; set; }

        public string bookName { get; set; }
        public string bookAuthor { get; set; }

        public string bookTranslator { get; set; }
      
        public DateTime registerDate { get; set; }

        
       public virtual ICollection<Category> Category { get; set; }
    }

 public class Category
    {

        public int CategoryId { get; set; }

        [StringLength(50)]
        public string categoryName { get; set; }

        [DataType(DataType.Text)]
        public string categoryDescription { get; set; }

        public virtual ICollection<Book> Books { get; set; }
    }



now i want to add category to my book
in controller:

 int catID = int.Parse(form["ddlCat"]);
 IEnumerable<Category> _cats = db.Categories.Where(x => x.CategoryId == catID);
 book.Category.Add(_cats.FirstOrDefault());
 db.Books.Add(book);
db.SaveChanges();



and in view:

<div class="form-group">
     <label class="control-label col-md-2" for="DepartmentID">Cats</label>
     <div class="col-md-10">
        @Html.DropDownList("ddlCat",new SelectList(ViewBag.Category,"Value","Text"))
                @Html.ValidationMessageFor(model => model.Category)
            </div>
        </div>



What I have tried:

i try to add user selected category but it give me error in below line

book.Category.Add(_cats.FirstOrDefault());



Object reference not set to an instance of an object.

解决方案

The debugger could have given you a hint of what's going on. To get the category you have to run FirstOrDefault on a IQueryable instead. What your code did was immediately treat the return of the query as an IEnumerable. If the query didn't return any rows the IEnumerable is going to be null. Since you can't call a method or property on null you get the exception message you got.

// Get the Category Id from the form
int catID = int.Parse(form["ddlCat"]);

// Get the Category object from the database
var category = db.Categories.Where(x => x.CategoryId == catID).FirstOrDefault();

// Did we get back a Category object?
if (category != null)
{
    // Add the Category to the Book Categories collection
    book.Category.Add(category);
}

// Add the Book to the Books table in the database
db.Books.Add(book);
db.SaveChanges();


这篇关于如何在实体框架中向导航属性插入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆