Reputation: 969
I have a problem with a simple class. One property of my class is a reference to another class, but when I read, it's always null.
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public String Description { get; set; }
public virtual Trademark Trademark { get; set; }
}
public class Trademark
{
public int TrademarkId { get; set; }
public String Description { get; set; }
}
Those are my classes, very simple. Then when I get the first element:
Product p = context.Products.First();
And p
contains the right product, but Trademark is null.
Even if I want to do a query using linq, like:
var prods = context.Products.Where(p => p.Trademark.TrademarkId == 1).ToList();
The database is generated Ok.
Using EF 4.3.1, with SqlServer compact edition 4.0
Thanks for any suggestions.
Add: This is my context class:
public class HPContext : DbContext
{
public HPContext()
: base()
{
this.Configuration.LazyLoadingEnabled = false; //Just for test
}
public DbSet<Product> Products { get; set; }
public DbSet<Trademark> Trademarks { get; set; }
}
Add: Database schema:
Table:
Products
Fields:
Id int primaryKey
Description nvarchar(4000)
Trademark_TrademarkId int
Table:
Trademarks
Fields:
TrademarkId int PrimaryKey
Description nvarchar(4000)
Upvotes: 2
Views: 2485
Reputation: 14919
You shall use Include
to include navigation properties if lazy loading is not enabled;
Product p = context.Products.Include("TradeMark").First();
Upvotes: 3