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