2

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)
3
  • Could you provide database schema? Apparently problem with associations... Commented May 17, 2012 at 13:51
  • Ok, i'll in my home in one hour and post the database... however, the database is generated with ef. Commented May 17, 2012 at 14:08
  • i could log to my computer and get the schema. Commented May 17, 2012 at 14:24

1 Answer 1

3

You shall use Include to include navigation properties if lazy loading is not enabled;

Product p = context.Products.Include("TradeMark").First();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but i got and exception: A specified Include path is not valid. The EntityType 'Product' does not declare a navigation property with the name 'Trademark'.
Sorry, i make a mistake, i re-tried with "Trademark" and works. is there any other simpler way? Because product will have several references?. Thanks
@Gabriel, you may enable lazy loading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.