在这里,我编写了一个简单的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; }
}
这里的主题= x.Name +“” x.Email如何分配该值
答案 0 :(得分:1)
因此,您将从方法GetEnqDetails()
获取Employee详细信息,您可以使用这些详细信息创建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;
}
}
根据评论进行更新:
注释中指定了DataType不匹配,即EnqId为int,n.Id为string。请相应地更正它们。我只是在代码中将参数更改为字符串。因为比较(if (EnqId != null)
的含义是较少,所以该值是整数。因此,如果您使用int
转发,请删除条件
答案 1 :(得分:1)
首先,您的GetEnqDetails
方法参数应为string
,因为您在Id
类中的Employee
的数据类型为string
。
然后,您必须将查询结果投影到EmailContent
类,例如
public EmailContent GetEnqDetails(string EnqId)
{
if (!string.IsNullOrEmpty(EnqId))
{
var x = from n in db.Employee
where n.Id == EnqId
select new EmailContent { Subject = n.Name + " " + n.Email, Body = "get any property by typing n." };
return x.FirstOrDefault();
}
else
{
return null;
}
}