簡體   English   中英

如何在Entity Framework中將集合與另一個上下文中的實體映射?

[英]How to map collection with entity from another context in Entity Framework?

我有這個EF實體

    public class Show
    {
        private ICollection<Country> _allowedCountries;

        public virtual ICollection<Country> AllowedCountries
        {
            get { return _allowedCountries ?? (_allowedCountries = new List<Country>()); }
            set { _allowedCountries = value; }

        }

}

其中Country是來自另一個上下文的實體。

當我嘗試讀取屬性AllowedCountries時,出現關於沒有現有表的錯誤。

表'db1.countries'不存在

Show映射到db1.show表,Country映射到db2.countries

我的制圖國家和顯示表

    public class CountryMap : EntityTypeConfiguration<Country>
    {
        public CountryMap()
        {
            ToTable("countries", "db2");

//other non useful information

        }
    }

        public ShowMap()
        {
            ToTable("shows", "db1");

          HasMany(x => x.AllowedCountries) //I think problem here
                .WithMany()
                .Map(m =>
                {
                    m.ToTable("allowed_countries");
                    m.MapLeftKey("ShowID");
                    m.MapRightKey("CountryID");
                });
}

我認為該問題是由於映射錯誤AllowedCountries引起的

我認為您無法擁有來自不同上下文的相關實體。 您可能考慮使用鏈接服務器(MS SQL功能)使兩個表都對一個連接可見。

老實說,我認為您應該避免這種混亂。 也許您應該問自己為什么有兩個背景。

通常,您應該從需要的那一刻起打開一個上下文,並在完成時關閉它。 兩者之間的所有工作都是在一個工作單元中完成的。

暫無
暫無

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

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