0
我在創建數據庫時使用實體框架首先從代碼創建外鍵。查詢下面顯示的表格,並將數據投影到另一個模型中,如下所示。一切似乎都是正確的,儘管當我查詢數據時,由AddressId連接的列似乎不工作,我的「街道」列返回空白數據。EF Code First:添加外鍵關係Linq-to-Entity投影
namespace Mvc4Connect.ViewModels
{
[Table("PersonEntity")]
public class PersonEntity : EntityTypeConfiguration<PersonEntity>
{
//Constructor
public PersonEntity()
{
this.ToTable("TB008555", schemaName: "SchemaUser");
this.Property(c => c.PersonId).HasColumnName("CL005500");
this.Property(c => c.FirstName).HasColumnName("CL005545");
this.Property(c => c.LastName).HasColumnName("CL005550");
this.Property(c => c.AddressId).HasColumnName("CL044760");
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int PersonId { get; set; }
public String FirstName { get; set; } //firstname
public String LastName { get; set; } //lastname
[ForeignKey("AddressEntity")]
public int AddressId { get; set; }
public virtual ICollection<AddressEntity> AddressEntity { get; set; }
}
}
我包含連接AddressId
namespace Mvc4Connect.ViewModels
{
[Table("AddressEntity")]
public class AddressEntity : EntityTypeConfiguration<AddressEntity>
{
//Constructor
public AddressEntity()
{
this.ToTable("TB047697", schemaName: "SchemaUser");
this.Property(c => c.AddressId).HasColumnName("CL045695");
this.Property(c => c.Street).HasColumnName("CL042710");
this.Property(c => c.City).HasColumnName("CL044747");
this.Property(c => c.State).HasColumnName("CL047460");
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int AddressId { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
}
我的實體上下文
public class EntityContext : DbContext
{
public DbSet<PersonEntity> Persons { get; set; }
public DbSet<AddressEntity> Address { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new PersonEntity());
modelBuilder.Configurations.Add(new AddressEntity());
}
}
這第二個表是我想在我的API控制器使用查詢。
var dbv = new EntityContext();
var query = (from vt in dbv.Persons
from ad in dbv.Address
where vt.LastName.StartsWith(ln)
where vt.FirstName.StartsWith(fn)
where ad.AddressId == vt.AddressId
select new PersonVM() // Create new object for projection
{
PersonId = vt.PersonId,
FirstName = vt.FirstName,
LastName = vt.LastName,
Street = ad.Street, // Blank Street data
AddressId = vt.AddressId // Debug to assure Id is assigned
});
return query.ToList();