我在这里编写了简单的 where
条件 linq 查询我从数据库中获取数据,但我想将该数据分配给另一列。
员工
public class Employee
{
public string Id{ get; set; }
public string Name{ get; set; }
public string Email{ get; set; }
}
Linq 查询:
public Employee GetEnqDetails(int EnqId)
{
if (EnqId != null)
{
var x = from n in db.Employee
where n.Id == EnqId
select n;
return x.FirstOrDefault();
}
else
{
return null;
}
}
从 Employee
表中获取任何数据,我想将该数据分配给另一个类作为
public class EmailContent
{
public string Subject { get; set; }
public string Body { get; set; }
}
这里 subject =x.Name +""x.Email 我如何分配那个值
最佳答案
因此,您从 GetEnqDetails()
方法中获取员工详细信息,您可以使用这些详细信息创建 EmailContent
的新实例:
var employ = GetEnqDetails(101);
if (employ != null)
{
EmailContent emc = new EmailContent() { Subject = String.Format("{0} {1}", employ.Name, employ.Email), Body = "" };
// proceed with emc
}
如果您不想使用过滤后的员工详细信息,唯一的要求是用员工详细信息实例化 EmailContent
意味着您可以像下面这样更改方法:
public static EmailContent GetEnqDetails(string EnqId)
{
if (EnqId != null)
{
return db.Employee.Where(n => n.Id == EnqId)
.Select(x => new EmailContent()
{
Subject = String.Format("{0} {1}",
x.Name, x.Email),
Body = ""
}).FirstOrDefault();
}
else
{
return null;
}
}
根据评论更新:
注释中指定的数据类型不匹配,即 EnqId 是 int,n.Id 是字符串。请相应地更正它们。我只是在我的代码中将参数更改为字符串。因为比较 (if (EnqId != null)
) 在值是整数时意义不大。因此,如果您使用 int
转发,请删除条件
关于c# - 当我们通过 id 获取记录时使用 Linq 查询如何将该值分配给另一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52714081/