如何在Linq to EF中以列表形式将数据添加到Class Object C#中?

sz81bmfz  于 2023-09-28  发布在  C#
关注(0)|答案(1)|浏览(86)

我的类用户是,

public class User
{
    public string Username
    {
        get;
        set;
    }
    public string Password
    {
        get;
        set;
    }
    public string [] RoleName
    {
        get;
        set;
    }
}

连接到EF,

var innerJoinQuery =
                                (from u
                                in db.Users
                                join ur in db.UserRoles
                                    on u.UserID equals ur.UserID
                                join r in db.Roles on ur.RoleID equals r.RoleID
                                select new {
                                    Username=u.Username,
                                    Password=u.Password,
                                    RoleName = r.RoleName, }).ToList();

其结果是,

Username = "Abc" Password="123"  RoleName = "Admin"
Username = "Test" Password="1234"  RoleName = "User"
Username = "Abc" Password="123"  RoleName = "Super User"

手动在User类对象中添加数据,

List<Models.User> UserList = new List<Models.User>();
UserList.Add(new Models.User { Username ="Abc",Password="123",RoleName = new string[] {"Admin","Supe User"} });
UserList.Add(new Models.User { Username = "Test", Password = "1234", RoleName = new string[] { "User" } });

如何在列表对象中添加linq查询数据如果你不明白我的问题,请告诉我
谢谢
编辑日期:
这不是这些值的硬编码,它可以比这更多,这取决于查询结果

ozxc1zmp

ozxc1zmp1#

你有没有试过示例化匿名类型而不是Models.User

var resultList = (
       ...
       select new {
            Username=u.Username,
            Password=u.Password,
            RoleName = new [r.RoleName] }
   )
   .ToList();

resultList.Add(new {
            Username=u.Username,
            Password=u.Password,
            RoleName = r.RoleName })

在这两种情况下,字段的编号和名称应相同。

更新

如果你想反过来做,那么把innerJoinQuery select语句改为选择Models.User,而不是匿名类型:

var innerJoinQuery = (
       ...
       select new Models.User {
            Username=u.Username,
            Password=u.Password,
            RoleName = new [] {r.RoleName} // assuming you have string in database
       }
   )
   .ToList();

UserList.AddRange(innerJoinQuery);

如果你想在查询中加入本地集合,那么AFAIK是不可能的,因为EF将无法将其转换为SQL。

更新2

您的EF版本遗漏了Models.UserThe array type 'System.String[]' cannot be initialized in a query result中的数组。所以在ToList之后引入一个新的Select是您的出路:

var innerJoinQuery = (
       ...
       select new  {
            Username=u.Username,
            Password=u.Password,
            RoleName = r.RoleName
       }
   )
   .ToList()
   .Select(u => new Models.User {
            Username=u.Username,
            Password=u.Password,
            RoleName = new [] {r.RoleName}
       });

UserList.AddRange(innerJoinQuery);

相关问题