|
我有映射現(xiàn)有數(shù)據(jù)庫(kù)的問(wèn)題.
2桌(簡(jiǎn)化)
"SomeEntity"
Id int
Name nvarchar
和
"EntityProperty"
EntityId int
Name nvarchar
并且從實(shí)體到實(shí)體屬性具有一對(duì)多的關(guān)系.
我如何使用EF 4.1 Code First進(jìn)行映射?
Thx提前.
編輯1:
好的)這是我的代碼
class Program
{
static void Main(string[] args)
{
var context = new DataContext();
var result = context.SomeEntity.Include(p => p.EntityProperties);
foreach (var entity in result)
{
Console.WriteLine(entity);
}
}
}
public class SomeEntity
{
public int EntityId { get; set; }
public string Name { get; set; }
public virtual ICollection<EntityProperty> EntityProperties { get; set; }
public override string ToString()
{
return string.Format("Id: {0}, Name: {1}", EntityId, Name);
}
}
public class EntityProperty
{
public int EntityId { get; set; }
public string Name { get; set; }
}
public class DataContext : DbContext
{
public DbSet<SomeEntity> SomeEntity { get { return this.Set<SomeEntity>(); } }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeEntity>().ToTable("SomeEntity");
modelBuilder.Entity<SomeEntity>().HasKey(k => k.EntityId);
modelBuilder.Entity<EntityProperty>().ToTable("EntityProperty");
modelBuilder.Entity<EntityProperty>().HasKey(k => k.EntityId);
}
}
在查詢獲取屬性時(shí)使用Include時(shí)出現(xiàn)問(wèn)題:
列名稱“SomeEntity_EntityId”無(wú)效. 列名稱“SomeEntity_EntityId”無(wú)效. 解決方法:
public class SomeEntity
{
public int SomeEntityId {get;set;}
public string Name {get;set;}
public ICollection<EntityProperty> EntityProperties {get;set;}
}
public class EntityProperty
{
public int EntityPropertyId {get;set;}
public string Name {get;set;}
}
創(chuàng)建ICollection(在關(guān)系的“1”側(cè))應(yīng)足以設(shè)置1:N關(guān)系.它將在EntityProperty表中創(chuàng)建SomeEntity_Id(或SomeEntityId)列.
編輯:順便說(shuō)一句:如果要啟用延遲加載,可以將該集合設(shè)置為虛擬.
public virtual ICollection<EntityProperty> EntityProperties {get;set}
編輯:
public class SomeEntity
{
[Key]
public int Id {get;set;}
public string Name {get;set;}
}
public class EntityProperty
{
// What is PK here? Something like:
[Key]
public int Id {get;set;}
// EntityId is FK
public int EntityId {get;set;}
// Navigation property
[ForeignKey("EntityId")]
public SomeEntity LinkedEntity {get;set;}
public string Name {get;set;}
}
首先嘗試這個(gè)…然后你可以再次添加ICollection,這次我沒(méi)有包含它以保持簡(jiǎn)單(你還是一個(gè)查詢屬性..但是:context.EntityProperties.Where(x => x.EntityId == X);) 來(lái)源:https://www./content-1-270551.html
|