簡體   English   中英

“無法定義兩個對象之間的關系,因為它們被附加到不同的ObjectContext對象。” -錯誤

[英]'The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.' - Error

首先,我想提一下,我已經搜尋了互聯網以找到解決問題的方法,但是我什么都沒做。 我是EF的新手,因此我對DBContext或ObjectContext沒有完全的了解,因此可能需要進一步的解釋。 我的EF代碼是首先建立數據庫的。

我的場景

我的數據模型中有兩個表: 在此處輸入圖片說明

下面是我的DriveDB類,其中附加了Client_Type(以及為簡單起見,本示例中未列出的其他類)。

public partial class DriveDB : DbContext
{
    public DriveDB()
        : base("name=DriveDB")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Client_Type> Client_Type { get; set; }
    public virtual DbSet<Entity> Entities { get; set; }
    public virtual DbSet<EntityContact> EntityContacts { get; set; }
    public virtual DbSet<Person> People { get; set; }
}

public class DataAccessService : IDataAccessService
{
    DriveDB MainRepository;
    public DataAccessService()
    {
        MainRepository = new DriveDB();
    }
    public void CommitChanges()
    {
        MainRepository.SaveChanges();
    }
}

我的邏輯是,由於現在附加了Client_Type表,因此我需要執行的所有更新操作都是運行.SaveChanges()方法,並且兩個表都將被更新。 但事實並非如此,因為它們顯然不共享相同的ObjectContext 我意識到DBContextObjectContext之間存在DBContext ,但是我不知道如何克服這個問題。

我試圖分離Client_Type並將其附加到DriveDB但是我從未找到正確的解決方案。

如何在不引發編譯器異常的情況下更新數據庫?

Xaml:

<ComboBox Style="{StaticResource DataComboBox}" ItemsSource="{Binding Client_type_list}" SelectedItem="{Binding Record.Client_Type, Mode=TwoWay}" ItemTemplate="{StaticResource Client_typeDataTemplate}"/>

<DataTemplate x:Key="Client_typeDataTemplate">
            <TextBlock Text="{Binding client_type1}"/>
        </DataTemplate>

您必須將狀態更新為修改后的每個表中的每個條目。 這些表是相關的,但是它們在您的DbContext中仍然是單獨的表。 您可以在此處詳細了解您的案件: http : //www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/updating-related-data-with NET MVC應用程序中的實體框架

因此,對於那些對此感興趣的人,是我找到的解決方案。

我的ComboBox ItemSource已綁定到此屬性:

public List<Client_Type> Client_type_list
{
   get { return ServerPxy.GetClientTypes(); }
}

這使得ComboBox不僅無法從Record屬性讀取SelectedItem值,而且在嘗試使用新值更新數據庫時也引發了上述異常。

我現在有一個僅在加載UserControl時從數據庫獲取值的屬性:

private List<Client_Type> client_type_list;
public List<Client_Type> Client_type_list
{
    get { return client_type_list; }
    set
    {
        client_type_list = value;
        RaisePropertyChanged("Client_type_list");
    }
}

public void LoadExecute()
{
    Client_type_list = ServerPxy.GetClientTypes();
}

重申一下...我相信SelectedItem的的ComboBox必須在之前設置ItemSource

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM