从View Model - EF Code First添加现有实体到集合

时间:2013-02-12 11:50:47

标签: asp.net-mvc collections ef-code-first

我正在尝试将现有用户添加到我的MVC控制器CreateMessage操作中的Recipients集合中,该操作传递一个CreateMessageViewModel,它应该填充我的域Message对象。

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

收件人是我在视图中选择的已发布用户ID,而正文是邮件正文。

我的域名对象如下:

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; }                        

}

我的控制器操作和存储库如下:

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);           
    }

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

如何在不从数据库中提取用户实体的情况下将其附加到“收件人”集合中?我正在使用ASP.NET MVC tutorials中所述的存储库模式的相同实现。

使用上面的代码我得到以下异常:

  

存储更新,插入或删除语句会影响意外   行数(0)。自那以后,实体可能已被修改或删除   实体已加载。刷新ObjectStateManager条目

1 个答案:

答案 0 :(得分: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)