Search code examples
c#frameworksentity

Entity framework query add data from select


I am having a query written in C# with Entity Framework :

            var query = _context.MyTable
            .Where(m => m.Id == request.MessageId && m.MessageStatusId == MessageStatusValue.Error)
            .Select(m => new Message()
            {
                Id = m.Id,
                MessageContentId = m.MessageContentId,
                FullContent = m.FullContent,
                CompanyCode = m.CompanyCode,
                Environment = m.Environment,
                MessageTime = m.MessageTime,
                MessageType = m.MessageType,
                QueueName = m.QueueName,
                QueueSeqNo = m.QueueSeqNo,
                Reciever = m.Reciever,
                ResponseMessageId = m.ResponseMessageId,
                Sender = m.Sender,
                ModTime = modInfo.ModTime,
                ModUserId = modInfo.ModUserId,
                MessageDirectionId = MessageDirectionValue.Out,
                MessageStatusId = MessageStatusValue.NotSent,

            });

And next I want to Add it to my database using var entity:

            var entity = _context.MyTable.Add(new Message()
        {
            Id = Guid.NewGuid(),
        }).Entity;

But I want to have every data from Select written above. How do I do that?


Solution

  • First of all you have to execute the query to get the results from the query. You can execute the query with ToList()

            var messages = _context.MyTable
                .Where(m => m.Id == request.MessageId && m.MessageStatusId == MessageStatusValue.Error)
                .Select(m => new Message()
                {
                    Id = m.Id,
                    MessageContentId = m.MessageContentId,
                    FullContent = m.FullContent,
                    CompanyCode = m.CompanyCode,
                    Environment = m.Environment,
                    MessageTime = m.MessageTime,
                    MessageType = m.MessageType,
                    QueueName = m.QueueName,
                    QueueSeqNo = m.QueueSeqNo,
                    Reciever = m.Reciever,
                    ResponseMessageId = m.ResponseMessageId,
                    Sender = m.Sender,
                    ModTime = modInfo.ModTime,
                    ModUserId = modInfo.ModUserId,
                    MessageDirectionId = MessageDirectionValue.Out,
                    MessageStatusId = MessageStatusValue.NotSent,
    
                }).ToList();
    

    Then you have a list of results which your are selected and you can add them to the db. You can add every single message to the db or use AddRange(messages)

    You can read more about it here