繁体   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