开发者

records being deleted when creating and adding new record via Linq To SQL & MVC3

开发者 https://www.devze.com 2023-03-19 17:59 出处:网络
I am trying to add a new comment to a comment table but all records in the table are being deleted with the exception of the one I added.

I am trying to add a new comment to a comment table but all records in the table are being deleted with the exception of the one I added. As an example: Let say I have an existing comment in the database for customer 1. I want to add a new comment.

In my controller I have the following:

  List<CustomerComment> comments = _commentsRepository.CustomerComments.ToList();


            CustomerComment newComment = new CustomerComment()
            {
                CustId = 1,
                RevisionNumber = revNumber,
                Comment = comment,
                Customer = _commentRespository.GetCustById(1),
                CommentDate = DateTime.Now,
                UserId = 24,
                Users = _commentsRepository.GetUserById(24)
            };


            comments.Add(newComment);

            _commentsRepository.SaveComment();

In my repository I have the following:

public Int32 SaveComment(CustomerComment comment)
{
    try
    {

        _DB.Sub开发者_高级运维mitChanges();
    }
    catch
    {
        throw;
    }

    return comment.CommentId;

}

While stepping through I see no changes to the data until after I create the new comment and step into the SaveComment method. What is strange is that it shows the comments already in the table for Delete and the new comment for insert.

Not understanding why it thinks the existing comments should be deleted.

I have also tried InsertOnSubmit but it does the samething so I took it out.

One thing I have noticed is that the existing comment after loading in the controller (comments) has the customer object as null. When I create the new comment I am assigning the customer to the new comment (Customer = _commentRespository.GetCustById(1).) Is this causing the delete and why doesn't the object get created and assigned when loaded.

Some additional information is that I am using POCOs and an XML mapping file.


Maybe you should not add the comment to an in memory storage try adding the new comment to the data context instead. I am presuming in your repository you have the add method... So something like _commentsRepository.add(newComment); shoukd work...

Regardless of that, why are you storing the whole customer in the database and for that matter user? you should be storing only their ids no? when you need read onky data to be thrown out into the view you may require additional data such as the customer and user details, use a dto object for that. Persistance in one thing, viewing data with certain data possibly populated from various tables is another thing...

0

精彩评论

暂无评论...
验证码 换一张
取 消