簡體   English   中英

如何將一個類添加到另一個具有一對多關系的類

[英]How to add a class to another class that has a one-to-many relationship

我有一個系統,用戶可以在其中登錄並創建板。 為此,有兩個單獨的類“用戶”和“董事會”。

public class User
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string UserType { get; set; }
    public DateTime LastLoginDate { get; set; }
    public virtual ICollection<Board> Boards { get; set; }
    public virtual ICollection<Post> Posts { get; set; }

public class Board
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime DateCreated { get; set; }
    public virtual ICollection<Post> Posts { get; set; }

我有一個 webform 來創建一個板,每當我嘗試運行該站點時,我都會收到 NullReferenceException。

public partial class AddBoard : System.Web.UI.Page
{
    Board board = new Board();
    User user = new User();
    Utility utility = new Utility();

    static User loggedInUser;
    static Board boardToAdd;

    protected void CreateButton_Click(object sender, EventArgs e)
    {
        string name = NameTextBox.Text;
        loggedInUser = (User)Session["loggedInUser"];

        string checkName = utility.CheckBoardName(name);
        if (checkName == "OK")
        {
            boardToAdd.Name = name;
            boardToAdd.DateCreated = DateTime.Now;
            user.AddBoard(boardToAdd, loggedInUser);


        }
        else
        {
            CreateLabel.Text = checkName;
        }
    }
}

異常發生在這一行:

boardToAdd.Name = name;

我正在嘗試調用此方法將板添加到 User 類:

public User AddBoard(Board board, User user)
    {
        BulletinContext _context = new BulletinContext();
        User _user = _context.Users.Find(user.ID);

        _context.Boards.Add(board);
        _context.Users.Add(user);
            return null;

    }

編輯:該錯誤已解決,但我仍然無法創建附加到用戶的板。 為了澄清起見,每個板都有一個“User_ID”,它應該是創建板的用戶的 ID。

編輯2:

這是 Board 的表格布局

它由 ID、名稱、創建日期和創建板的用戶 ID 組成。

這是因為您沒有初始化 boardToAdd 對象,它的初始值為 null。 嘗試創建板的實例。

static Board boardToAdd = new Board();

看起來您還沒有定義外鍵。 所以你需要做類似的事情。

public User AddBoard(Board board, User user)
{
    BulletinContext _context = new BulletinContext();
    board.User_ID = user.ID;
    _context.Boards.Add(board);
        return null;

}

編輯:我在您的代碼中看不到 _context.SaveChanges()。 因此,如果它不存在,您可能需要添加它。

如果您定義了外鍵:

Change the User Class to create a new HashSet of Boards something like:

public User() 
{
     Boards = new HashSet<Board>();
}
public User AddBoard(Board board, User user)
{
    BulletinContext _context = new BulletinContext();
    User _user = _context.Users.Find(user.ID);
    _user.Boards.Add(board);
    return null;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM