简体   繁体   English

如何从不同的表中获取特定的列 ASP.NET 核心和实体框架核心

[英]How to get specific columns from different tables ASP.NET Core and Entity Framework Core

I Want to get some specific column from two tables different ChatMessage And ChatGroup.我想从两个不同的 ChatMessage 和 ChatGroup 表中获取一些特定的列。 So that after returning data only contain messageId, Message, SenderUserId, CreatedDate, ChatGroupId.这样返回数据后只包含messageId、Message、SenderUserId、CreatedDate、ChatGroupId。

The query returns all the information of the ApplicationUser and ChatGroup data including the email, hashed Password, user1, user2, again ChatMessages and many more I don't want.该查询返回 ApplicationUser 和 ChatGroup 数据的所有信息,包括 email、散列密码、user1、user2、 ChatMessages以及更多我不想要的信息。 So I tried by adding Select in implementation.所以我尝试在实现中添加Select

A error occur will Implementing this.执行此操作会发生错误。

Implementation:执行:

public  IEnumerable<ChatMessage> GetMessageInChat(ChatModel model)
{
    try
    {
        PutReadZero(model).Wait();
        return _context.ChatMessages.Where(userID => userID.ChatGroup.Id == model.GroupId)
            .OrderByDescending(m => m.CreatedDate)
            .AsEnumerable()
            .Reverse()
            .Select(p => new 
            {
                p.Id,
                p.Message,
                SenderUserId= p.SenderUser.Id,
                p.CreatedDate,
                ChatGroupId = p.ChatGroup.Id,
            })
            .ToList();
    }
    catch (Exception ex)
    {
        throw new NotImplementedException();
    }
}

ChatMessage.cs: ChatMessage.cs:

namespace ProjectName.Models
{
    public class ChatMessage
    {
        public int Id { get; set; }
        public string Message { get; set; }
        public string FileName { get; set; }
        public DateTime CreatedDate { get; set; }
        public ApplicationUser SenderUser { get; set; }
        public ChatGroup ChatGroup { get; set; }
    }
}

ChatGroup:聊天组:

namespace ProjectName.Models
{
    public class ChatGroup
    {
        public int Id { get; set; }
        public virtual ApplicationUser User1 { get; set; }
        public virtual ApplicationUser User2 { get; set; }
        public int User1Unread { get; set; }
        public int User2Unread { get; set; }
        public DateTime CreatedDate { get; set; }
        public virtual IEnumerable<ChatMessage> ChatMessages { get; set; }
    }
}

ChatModel.cs:聊天模型.cs:

namespace ProjectName
{
    public class ChatModel
    {
        public string SenderId { get; set; }
        public string ReceiverId { get; set; }
        public string Message { get; set; }
        public int GroupId { get; set; }
        public DateTime CreatedDate { get; set; }
        public IFormFile FileContent { get; set; }
    }
}

Error:错误:

Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: int Id, string Message, string SenderUserId, System.DateTime CreatedDate, int ChatGroupId>>' to 'System.Collections.Generic.IEnumerable<ProjectName.Models.ChatMessage>'.无法将类型“System.Collections.Generic.List<<匿名类型:int Id,字符串消息,字符串 SenderUserId,System.DateTime CreatedDate,int ChatGroupId>>”隐式转换为“System.Collections.Generic.IEnumer.Model.聊天消息>'。 An explicit conversion exists (are you missing a cast?)存在显式转换(您是否缺少演员表?)

That's because you specified your method should return an IEnumerable<ChatMessage> but your result is returning an anonymous type.那是因为你指定你的方法应该返回一个IEnumerable<ChatMessage>但你的结果返回一个匿名类型。 If this is an action method in a controller, simply return an IActionResult which allows any data type in its response如果这是 controller 中的操作方法,只需返回一个IActionResult允许其响应中的任何数据类型

public IActionResult GetMessageInChat(ChatModel model)
{
   ... 
    var result = _context.ChatMessages.Where(userID => userID.ChatGroup.Id == model.GroupId).OrderByDescending(m => m.CreatedDate).AsEnumerable().Reverse().Select(p => new { p.Id, p.Message, SenderUserId= p.SenderUser.Id, p.CreatedDate, ChatGroupId = p.ChatGroup.Id, }).ToList();
    return Ok(result);
} 

If it is not, remove the .Select(...) from your query in the original method.如果不是,请使用原始方法从查询中删除.Select(...)

return _context.ChatMessages.Where(userID => userID.ChatGroup.Id == model.GroupId) .OrderByDescending(m => m.CreatedDate).Reverse().ToList();

Then do the filtering with Select in the action method that calls the GetMessageInChat() .然后在调用GetMessageInChat()的操作方法中使用Select进行过滤。 The action method should return an IActionResult action 方法应该返回一个IActionResult

You can use FromSqlRaw and write the select query if you want only the data of table without any joins.如果您只想要表的数据而不需要任何连接,您可以使用 FromSqlRaw 并编写 select 查询。

`var data = _context.ChatMessages.FromSqlRaw("SELECT * from ChatMessages Where ChatGroupId = model.GroupId").ToList();`

In this way you will get all your required data通过这种方式,您将获得所有需要的数据

Have a new model that only contains the properties you want.拥有一个仅包含您想要的属性的新 model。

public class ChatMessageViewModel
{
    public int Id { get; set; }
    public string Message { get; set; }
    public int SenderUserId { get; set; }
    public int ChatGroupId { get; set; }
    public DateTime CreatedDate { get; set; }
}

Then select this model in the linq:然后linq中的select这个model:

.Select(p => new ChatMessageViewModel
{
    Id = p.Id,
    Message = p.Message,
    SenderUserId= p.SenderUser.Id,
    CreatedDate  = p.CreatedDate,
    ChatGroupId = p.ChatGroup.Id,
})

Then change the return type to IEnumerable<ChatMessageViewModel>然后将返回类型更改为IEnumerable<ChatMessageViewModel>

If you need strongly typed object from the GetMessageInChat method, then you should just go with the answer of @mj1313.如果您需要来自GetMessageInChat方法的强类型 object,那么您应该只使用 go 和 @mj1313 的答案。

But if you don't need a typed object (for example, if GetMessageInChat is an action method in some controller class), you can simply change the method signature to return a dynamic type -但是,如果您不需要类型化的 object(例如,如果GetMessageInChat是某些 controller 类中的操作方法),您可以简单地更改方法签名以返回dynamic类型 -

public dynamic GetMessageInChat(ChatModel model)

You can call the method as -您可以将该方法称为 -

var myList = myObject.GetMessageInChat(chatModel);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从不同的表创建 ASP Net Core Entity Framework 实体 - ASP Net Core Entity Framework entity creation from different tables 如何使用.net-core和Entity Framework Core和Identity从thenInclude中获取特定列? - How do i get specific columns from a thenInclude using .net-core and Entity Framework Core and Identity? 对ASP.NET Core上的Entity Framework使用其他连接提供程序 - Using a different connection provider for Entity Framework on ASP.NET Core ASP.NET Core MVC + Entity Framework Core 如何获取新添加的 object 的 id - How ASP.NET Core MVC + Entity Framework Core get the id of a newly added object 如何在 ASP.NET Core web 应用程序中使用 Entity Framework Core 从数据库中保存和检索图像? - How to save and retrieve images from database using Entity Framework Core in ASP.NET Core web application? ASP.NET Core MVC +实体框架+ GET +数组 - ASP.NET Core MVC + Entity Framework + GET + Array 实体框架 6.3 与 ASP.NET 核心 3 - Entity Framework 6.3 with ASP.NET Core 3 如何为ASP.net Core配置Entity Framework 6 - How to configure Entity Framework 6 for ASP.net Core 如何在ASP.NET Core项目中设置实体框架 - How to setup Entity Framework in ASP.NET Core project 使用ASP.NET Core 1.1身份和实体框架Core的不同用户类型 - Different user types with ASP.NET Core 1.1 Identity and Entity Framework Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM