实体框架 - DbContext SaveChanges()

时间:2016-03-24 21:12:36

标签: entity-framework dbcontext entities savechanges

有人可以告诉我是否可能,以及如果避免在此代码中使用两次_context.SaveChanges()

        Message m = new Message
        {
            Title = message.Title,
            Body = message.Body,
            Date = DateTime.Now
        };

        _context.Messages.Add(m);
        _context.SaveChanges();

        UserMessage messageToUser = new UserMessage
        {
            MessageID = m.ID,
            ProductID = message.ProductID,
            SenderID = message.SenderID,
            RecieverID = reciever.Id
        };

        _context.UserMessages.Add(messageToUser);
        _context.SaveChanges();

这就是我的实体的样子

public class UserMessage
{
    public int ID { get; set; }
    public string SenderID { get; set; }
    public string RecieverID { get; set; }
    public int? ProductID { get; set; }
    public int MessageID { get; set; }

    public User Sender { get; set; }
    public User Reciever { get; set; }
    public Product Product { get; set; }
    public Message Message { get; set; }
}

public class Message
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        public DateTime Date { get; set; }
    }

1 个答案:

答案 0 :(得分:1)

在UserMessage类中,您设置引用而不是外键,因为尚未知道外键。

在您的代码中,这意味着:

    Message m = new Message
    {
        Title = message.Title,
        Body = message.Body,
        Date = DateTime.Now
    };

    _context.Messages.Add(m);

    UserMessage messageToUser = new UserMessage
    {
        ProductID = message.ProductID,
        SenderID = message.SenderID,
        RecieverID = reciever.Id,
        Message = m
    };

    _context.UserMessages.Add(messageToUser);
    _context.SaveChanges();