C#MVC保存父和子1保存?

时间:2017-10-22 19:01:50

标签: c# asp.net-mvc nhibernate model

我的映射:

 public class MessageMap : ClassMap<Message>
{
    public MessageMap()
    {
        Table("[Messages]");
        Id(x => x.Id).Column("id");
        References(x => x.From).Column("user_id");
        Map(x => x.Subject).Column("subject");
        Map(x => x.Body).Column("body");
        Map(x => x.DateSent).Column("date_sent");
        HasMany(x => x.Recipients).KeyColumn("message_id").AsBag().LazyLoad().Cascade.AllDeleteOrphan();
    }
}

public class MessageRecipientMap : ClassMap<MessageRecipient>
{
    public MessageRecipientMap()
    {
        Table("[MessageRecipients]");
        Id(x => x.Id).Column("id");
        References(x => x.To).Column("user_id");
        References(x => x.Message).Column("message_id");
        Map(x => x.IsRead).Column("is_read");
        Map(x => x.DateRead).Column("date_read");
    }
}

我的模特:

public class Message : IEntity
{
    public virtual Guid Id { get; set; }
    public virtual User From { get; set; }
    public virtual string Subject { get; set; }
    public virtual string Body { get; set; }
    public virtual DateTime DateSent { get; set; }
    public virtual IList<MessageRecipient> Recipients { get; set; }

    public Message()
    {
        Recipients = new List<MessageRecipient>();
    }
}

public class MessageRecipient : IEntity
{
    public virtual Guid Id { get; set; }
    public virtual User To { get; set; }
    public virtual bool IsRead { get; set; }
    public virtual DateTime DateRead { get; set; }
    public virtual Message Message { get; set; }
}

我的ViewModel:

public class MessageModel
{
    [Required]
    public virtual Message Message { get; set; }

    public virtual IList<MessageRecipient> MessageRecipients { get; set; }
    public virtual string RecipientIds { get; set; }
    public virtual IList<UserLiteModel> AllowedMailingList { get; set; }
}

我的控制器代码:

public ActionResult Create(MessageModel model)
{
    var user = GetPrincipalUser();
    var sentDate = DateTime.Now;

    var message = new Message
    {
        From = user,
        DateSent = sentDate
    };
    var toUserIds = model.RecipientIds.Split(',').ToList();
    foreach (var uId in toUserIds)
    {
        var uGuid = Guid.Parse(uId);
        var messageRecipient = new MessageRecipient
        {
            To = _userService.Get(uGuid),
            IsRead = false,
            DateRead = sentDate
        };
        message.Recipients.Add(messageRecipient);
    }
    _messageService.Save(message);
    return RedirectToAction("Index");
}

我的问题:

当我在我的控制器中保存我的方法时,对于MessageRecipients,它总是为空。我是否真的必须首先保存消息然后分配它。好像很多工作。所以,让我发布这条消息,似乎不那么重要了。

1 个答案:

答案 0 :(得分:0)

点击here以获得答案,因为这对我有用。这也使用反向设置。