Entity Framework code first not working
I have a Class like this:
class ClassA
{
public long classAID {get; set;}
public string Description {get; set;}
public IEnumerable<ClassB> ClassBs {get; set;}
}
class ClassB
{
public long classBID {get; set;}
public string SomeOtherDescription {get; set;}
public IEnumerable<ClassA> {get; set;}
}
class TestContext: DBContext
{
public DbSet<ClassA> ClassAs {get; set;}
public DbSet<ClassB> ClassBs {get; set;}
}
H have the DB with same column names and table names as the classes and properties. I have done the web.config configuration as required. When i try to use above to retrieve the data i get the error
"System.Data.Edm.EdmEntityType: : EntityType 'ClassA' has no key defined. Define the key for this EntityType."
and
"System.Data.Edm.EdmEntityType: : EntityType 'ClassB' has no key defined. Define the key for this EntityType."
I tired multiple approaches such as setting 开发者_如何转开发the key attribute, Foreign key attribute etc. but nothing worked. Please let me know what am i missing.
I use C# 4 and i have verified with following URLs:
http://www.asp.net/mvc/tutorials/mvc-music-store-part-4http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx
Use this:
public class ClassA
{
public long ClassAID {get; set;}
public string Description {get; set;}
public virtual ICollection<ClassB> ClassBs {get; set;}
}
public class ClassB
{
public long ClassBID {get; set;}
public string SomeOtherDescription {get; set;}
public virtual ICollection<ClassA> {get; set;}
}
public class TestContext: DBContext
{
public DbSet<ClassA> ClassAs { get; set; }
public DbSet<ClassB> ClassBs { get; set; }
}
As you can see navigation properties are marked as virtual
. It will allow lazy loading = navigation property will be loaded separately first time your code access the property. It is not always the best way to load navigation properties this way because it causes additional roundtrips to the database. Because of that EF also offers eager loading where you explicitly tell EF to load your navigation property:
var query = context.ClassAs.Include(c => ClassBs);
精彩评论