[英]How to bind extra properties of partial class while executing sql query in entity framework?
我有一個具有動態where子句的sql查詢:
string qry= "select p.*,u.fname as username from Proforma p inner join users u on u.userid=p.userid where " + where1 + " and " + where2 + " and " + where3 + " order by p.userid,invoicedate desc";
我使用此添加了額外的屬性
namespace root.Models.db
{
public partial class Proforma
{
public string username { get; set; }
}
}
現在,我嘗試使用此功能一次獲取數據:
List<Proforma> pm = db.Database.SqlQuery<Proforma>(qry).ToList();
我期望它從數據庫獲取用戶名並進行相應的綁定。 但這是行不通的。
請幫忙。 提前致謝。
詳細設置用戶和Performa。
如果關系是一對一關系,並且兩個表共享一個UserId PK:
public class User
{
public int UserId {get; set;}
// .. other User fields.
public virtual Performa Performa {get; set;}
}
public class Performa
{
public int UserId {get; set;}
// .. other Performa fields.
public virtual User User {get; set;}
}
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
ToTable("Users");
HasKey(x => x.UserId)
.Property(x => x.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(x => x.Performa)
.WithRequiredPrincipal(x => x.User);
}
}
public class PerformaConfiguration : EntityTypeConfiguration<Performa>
{
public PerformaConfiguration()
{
ToTable("Performas");
HasKey(x => x.UserId)
.Property(x => x.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
從那里,我強烈建議使用ViewModels / DTO對象傳遞回調用視圖/代碼,而不是傳遞實體。 這避免了由於延遲加載而造成的各種性能痛苦,並減少了從DB到客戶端遍歷導線的數據量。
var performaQuery = db.Database.SqlQuery<Proforma>(qry);
var viewModels = performaQuery.Select(x => new PerformaViewModel
{
UserId = x.UserId,
PerformaName = x.Name,
UserName = x.User.Name
}).ToList();
使用這種方法,您可能可以減少或消除對動態查詢的需求。 如果您已將實體映射到關系,並且想通過說用戶名與PerformaName或InvoiceDate來加載Performa ...
public IEnumerable<PerformaViewModel> LoadByCriteria(string userName = null, string performaName = null, DateTime? invoiceDate = null)
{
var query = context.Performas.Where(x => x.IsActive); // Global filter example...
if (!string.IsNullOrEmpty(userName))
query = query.Where(x => x.User.UserName == userName);
if (!string.IsNullOrEmpty(performaName))
query = query.Where(x => x.PerformaName == performaName);
if (invoiceDate.HasValue)
query = query.Where(x => x.InvoiceDate == invoiceDate);
var viewModels = query.Select(x => new PerformaViewModel
{
UserId = x.UserId,
PerformaName = x.Name,
UserName = x.User.Name
}).ToList();
return viewModels;
}
那只是組成Linq表達式的一個基本示例。 您將需要詳細說明上下文的范圍,無論是使用工作單元還是使用由IoC容器提供,或由using()
塊聲明的,針對該請求的DB Context。 EF將使用條件WHERE子句執行該子句,並在必要時將適用的條件進行“與”運算,並僅返回所選字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.