2015-08-26 7 views
1

У меня есть неприятная проблема с моим кодом. Моя модель:Вставка сложного типа Entity Framework

public class Option 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Conference> Conference { set; get; } 
} 

public partial class Conference 
{ 
    [Key, ForeignKey("User")] 
    public int UserId { get; set; } 
    public virtual Option Option { set; get; } 
    public virtual User User { get; set; } 
} 

public partial class User 
{ 
    public int Id {get; set; } 
    public string Name { get; set; } 
    public virtual Conference Conference { get; set; } 
} 

И теперь I`m получает объект Option из Db по dbSet.Find (ID) (RepositoryFactory) и то, что я хочу сделать это, чтобы сохранить вновь созданный пользователем, но с выбранной опцией.

Если я сделать так:

var option = dbSet.Find(id); 
      var user = new User() 
      { 
       Name = "Name", 
       Conference = new Conference 
       { 
        Option = option 
       } 
      }; 
//... 
context.SaveChanges(); 

I`m получаю исключение: Объект объект не может ссылаться несколько экземпляров IEntityChangeTracker.

Что я делаю неправильно?

Редактировать: Я пытался создать картографию, но это тоже не работает.

modelBuilder.Entity<Conference>() 
       .HasKey(x => x.UserId) 
       .HasRequired(x => x.User) 
       .WithOptional(user => user.Conference); 

      modelBuilder.Entity<Option>() 
       .HasMany(option => option.Conferences) 
       .WithRequired(conference => conference.Option) 
       .HasForeignKey(conference => conference.UserId); 

ответ

0

Вы пытаетесь достичь взаимосвязи между пользователем и конференцией 1: 1? Если это так, вам нужно добавить свойство Id (ключ) для пользователя. Пожалуйста, ознакомьтесь с комментариями, которые я добавил к образцу кода ниже относительно отношения 1: 1. Я бы посоветовал провести дальнейшую оценку вашего домена, чтобы убедиться, что это то, чего вы пытаетесь достичь ...

using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.ComponentModel.DataAnnotations.Schema; 
using System.Data.Entity; 

namespace Stackoverflow 
{ 
    public class EntityContext : DbContext 
    { 
     public IDbSet<Conference> Conferences { get; set; } 
     public IDbSet<Option> Options { get; set; } 
     public IDbSet<User> Users { get; set; } 
    } 

    public class Option 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public virtual ICollection<Conference> Conference { set; get; } 
    } 

    public class Conference 
    { 
     // In one-to-one relation one end must be principal and second end must be dependent. 
     // User is the one which will be inserted first and which can exist without the dependent one. 
     // Conference end is the one which must be inserted after the principal because it has foreign key to the principal. 

     [Key, ForeignKey("User")] 
     public int UserId { get; set; } 
     public int OptionId { get; set; } 
     public virtual Option Option { set; get; } 
     public virtual User User { get; set; } 
    } 

    public class User 
    { 
     // user requires a key 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public virtual Conference Conference { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      using (var entityContext = new EntityContext()) 
      { 
       // added to facilitate your example 
       var newOption = new Option {Name = "SomeOptionName"}; 
       entityContext.Options.Add(newOption); 
       entityContext.SaveChanges(); 

       var option = entityContext.Options.Find(newOption.Id); 

       var user = new User 
       { 
        Name = "Name", 
        Conference = new Conference 
        { 
         Option = option 
        } 
       }; 

       // need to add the user 
       entityContext.Users.Add(user); 

       //... 
       entityContext.SaveChanges(); 
      } 
     } 
    } 
} 
+0

Это все еще не помогает. Ошибка остается. – Lubudubu1010

+0

Я проверил примерный код выше, и он выполнит. Попробуйте скопировать/вставить ВСЕ код выше в консольное приложение. –

Смежные вопросы