0

I am trying to add existing users to my Recipients collection in my MVC controllers CreateMessage action which passes a CreateMessageViewModel which should populate my domain Message object.

 public class CreateMessageViewModel
{
    public string Body { get; set; }
    public ICollection<int> Recipients { get; set; }
}

Recipients are the posted user ID's I've selected in my view and the body is the message body.

My domain object is as follows:

public partial class Message : ModelBase
{
    public Message()  {
        this.Recipients = new HashSet<User>();
    }

    [Key]
    public int Id { get; set; }

    public int SenderId { get; set; }

    [ForeignKey("SenderId")]
    public virtual User Sender { get; set; }

    public virtual ICollection<User> Recipients { get; set; }

    public string Body { get; set; }                        

}

My controller action and respository is as follows:

UnitOfWork db = new UnitOfWork();

[HttpPost]
    public ActionResult Create(Model.ViewModel.CreateMessageViewModel messagevm)
    {
        if (ModelState.IsValid)
        {
            var CurrentUserId = WebSecurity.CurrentUserId;

            MessageNotification message = new MessageNotification();
            message.Message = new Message
            {
                Body = messagevm.Body,
                SenderId = CurrentUserId      
            };

            foreach (int userId in messagevm.Recipients)
            {
                // How do I add the existing recipients here?
                // I get an exception here if I run this code and then save...
                User recipient = new User { UserId = userId };
                db.UserRepository.Attach(recipient);
                message.Message.Recipients.Add(recipient); 
            }

            message.Sent = DateTime.Now;
            message.UserId = CurrentUserId;

            db.MessagingRepository.Add(message);
            db.Save();

            return RedirectToAction("Index");
        }

        return View(messagevm);
    }


public class Repository<TEntity> : IDisposable where TEntity : class 
{
    internal MyDB Context; 
    internal DbSet<TEntity> dbSet;

    public Repository(MyDB context)
    {
        this.Context = context;
        this.dbSet = Context.Set<TEntity>();
    }                

    public virtual void Attach(TEntity entityToAttach)
    {
        dbSet.Attach(entityToAttach);           
    }

    ............
}

How do I attach the user entities to the Recipients collection without fetching them from the database? I am using the same implementation of the repository pattern as stated in the ASP.NET MVC tutorials .

With the code above I get the following exception:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries

4

1 回答 1

0

你可以做

var user = new User { UserId = userId };
db.Users.Attach(user);
message.Message.Recipients.Add(user);

您可能需要检查用户是否已在上下文中加载:

var user = db.Users.Local.FirstOrDefault(u => u.UserId == userId);
if (user == null)
... // create and attach user as above.

编辑

您的修改让我注意到这db不是一个上下文,而是一个工作单元。您可以将上面的逻辑包装在一个方法中db.MessagingRepository,例如GetUser(int userId).

于 2013-02-12T13:12:23.040 回答