Object structure 4.1. The problem with the First and One-to-Many list.

I have a problem displaying an existing database.

2 tables (simplified)

"SomeEntity" Id int Name nvarchar 

and

 "EntityProperty" EntityId int Name nvarchar 

and are related one-to-many from Entity to entity properties.

How can I match this using the first EF 4.1 code?

thanks in advance.

Edited 1:

ok) this is my code

 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); } } 

The problem is when I use Include in the request to get properties:

Invalid column name 'SomeEntity_EntityId'. Invalid column name "SomeEntity_EntityId".

+4
source share
2 answers

I solved the problem. I cannot add a simple PK to a relational table. I added a comprehensive PK on all unique fields and matched one-to-many. It's all.

+1
source
 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;} } 

Creating this ICollection (on the “1” side of the relationship) should be sufficient to set the 1: N relationship. It will create the SomeEntity_Id (or SomeEntityId) column in the EntityProperty table.

Edit: Btw: you can set this collection to virtual if you want lazy loading to activate.

 public virtual ICollection<EntityProperty> EntityProperties {get;set} 

Edit:

 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;} } 

Try this first ... then you can add that ICollection again, I did not turn it on this time to keep it simple (and you still request properties .. but with: context.EntityProperties.Where(x=>x.EntityId == X); )

+3
source

All Articles