Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 21st, 2012  |  syntax: None  |  size: 1.40 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Entity Framework 4.1 RTW Code First - Does POCO one to many need reference to child entity and child entities primary key?
  2. public class Parent
  3. {
  4.     public int Id
  5.     {
  6.         get;
  7.         set;
  8.     }
  9.  
  10.     public int ChildId
  11.     {
  12.         get;
  13.         set;
  14.     }
  15.  
  16.     public virtual Child Child
  17.     {
  18.         get;
  19.         set;
  20.     }
  21. }
  22.  
  23. public class Child
  24. {
  25.     public int Id
  26.     {
  27.         get;
  28.         set;
  29.     }
  30. }
  31.  
  32. public class ParentMapping : EntityTypeConfiguration<Parent>
  33. {
  34.     public ParentMapping()
  35.     {
  36.         HasKey(x => x.Id);
  37.  
  38.         HasRequired(X => x.Child)
  39.             .WithMany()
  40.             .Map(x => x.ToTable("Parent")
  41.                         .MapKey("ChildId"));
  42.     }
  43. }
  44.        
  45. public class Parent
  46. {
  47.     public int Id
  48.     {
  49.         get;
  50.         set;
  51.     }
  52.  
  53.     public virtual Child Child
  54.     {
  55.         get;
  56.         set;
  57.     }
  58. }
  59.        
  60. var parent = GetUpdatedParentSomehow();
  61. // Dummy object for the old child if the relation is not loaded
  62. parent.Child = new Child { Id = oldChildId };
  63. // Attach the parent
  64. context.Parents.Attach(parent);
  65.  
  66. // Create dummy for new child (you can also load a child from DB)
  67. var child = new Child { ID = newChildId };
  68. // No attach the child to the context so the context
  69. // doesn't track it as a new child
  70. context.Childs.Attach(child);
  71. // Set a new child
  72. parent.Child = child;
  73. // Set parent as modified
  74. context.Entry(parent).State = EntityState.Modified;
  75. context.SaveChanges();