0

i'm trying to add a new entity in my context like that :

article.Id = 1;
var rede = from r in mycontext.Redevable.AsNoTracking()
           where r.Matricule == "0001414"
           select r;

article.Redevable = rede.First<Redevable>();
...

mycontext.Article.Add(article);
mycontext.SaveChanges();

and i get a DbEntityValidationException saying that the Redevable is mandatory because the property "Redevable" is marker as Required.

It works fine if i remove "AsNoTracking" but the performance are very bad.

Could you help me ?

Thanks in advance.

  • What does "very bad performance" mean? This query just materializes a single object. Anyway, you must attach `rede` to the context to avoid duplication of this object in the database. So, removing `AsNoTracking` is the correct approach. – Slauma Oct 27 '11 at 14:18

2 Answers2

1

You can create a Fk Property only with the Id like this:

public int RedevableId { get; set; }

public Redevable Redevable{ get; set; }

and then set it from the Redevable instance:

article.RedevableId = rede.First<Redevable>().Id;  

then persist your changes:

mycontext.Article.Add(article);      
mycontext.SaveChanges();
marianosz
  • 1,234
  • 10
  • 8
0

AsNoTracking() means that you cant update these entities without reattaching them to the tracking graph. For more details see

// Attaches the entity and then save
context.Entry(article).State = EntityState.Modified;
context.SaveChanges();
Community
  • 1
  • 1
Moji
  • 5,720
  • 2
  • 38
  • 39