EF数据库ASP.NET Core 2.2添加子对象

时间:2019-05-01 11:09:46

标签: asp.net database entity-framework

我是asp.net的新手,我正在尝试使用实体框架创建关系数据库。不幸的是,我对如何更新子对象以及哪个表应该包含ID感到困惑。

很抱歉代码中有任何错别字-它是经过修改的版本,因此我不会发布无意义的代码。

 public class Book
    {
    public Book()
    {

    }

    public Book(BookViewModel book)
    {
        //Child table
        Author author = new Author(book);
        Author = author;
        //
        Length = book.length           
        Status = "Borrowed";          
    }



    [Key, Required]
    public int BookId { get; set; }

    [Required]
    public string Author { get; set; }

    [Required]
    public int Length { get; set; }

    public virtual Author author { get; set; }

    public virtual ICollection<CNote> Notes { get; set; }

}

public class Note
{

    public Note()
    {
    }

    public Note(User user, Message message)
    {            
        User = user;      
        Message = message;
    }

    [Required, Key]
    public int NoteId { get; set; }

    public string User { get; set; }

    public string Message { get; set; }

    (Here BookId is auto generated by the migration in the database and is not in the model)

}

    public class Author
{

    public Author()
    {
    }

    public Author(BookViewModel book)
    {            
        Name = book.Name;  

    }

    [Required, Key]
    public int AuthorId { get; set; }

    public string Name { get; set; }

    //The migration kept auto-generating the AuthorId to be in Book, rather than BookId to be in Author. So I had to add

    public Book book;

    public int BookId;

}

默认情况下,Note对象在迁移表中以BookID字段结尾,但是对于Author,AuthorId字段在Book中结尾-尽管对象非常相似(一对多或一对一除外) 。这意味着Author现在在模型和数据库中都具有BookId。

在我的页面模型中:

Note note = new Note(user, message);

Book book = _context.Book.First(x => x.BookId == id);

        if (book.Note == null)
        {
            book.Note = new List<Note>() { note };
        }
        else
        {
            book.Note.Add(note);
        }

        try
        {
            await _context.SaveChangesAsync();
        }

不过,哪种方法可以正常工作

Book book = new Book(BookModelView book);      

        try
        {
            _context.Ticket.Add(book);
            await _context.SaveChangesAsync();
        } 

未正确添加作者对象-表为空,并且在检查book对象时,BookID生成为-27xxx。这可能是因为我必须在作者中指定BookId,因此不会自动添加书的BookID。我真的不明白为什么注释集合默认情况下采用BookId,但是一对一关系将authorId添加到Book中。

不幸的是,由于bookId直到生成书添加到上下文时才生成,因此我无法手动将其添加到作者(我也不认为我也必须这样做,因为我不使用Notes)。

做到这一点的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

没关系-似乎与带有AuthorId的书一起正常工作。

我将其恢复为以前的样子,现在可以正常工作了(我必须更改了其他内容)。