每次我上傳一個新的圖像並將其與一個配置文件鏈接,它也會在錯誤的數據庫中創建一個新的配置文件。爲什麼MVC創建所有這些新的配置文件?
我想象它是通過這個代碼創建:
var imageMeta = new ImageMeta
{
Name = imageForm.Name,
User = Profile,
};
...
db.Images.Add(imageMeta);
db.SaveChanges();
凡Profile
來自我BaseController
:
public class BaseController : Controller
{
private UsersContext _udb = new UsersContext();
private UserProfile _profile = null;
public new UserProfile Profile
{
get
{
if(_profile == null && User.Identity.IsAuthenticated)
{
_profile = _udb.UserProfiles.Single(p => p.UserName == User.Identity.Name);
}
return _profile;
}
}
}
這種方法,Profile.get
,翻出了登錄用戶從正確的個人資料UsersContext
,但第一個片段中的db
實際上是GalleryContext
。
我猜測它沒有在該數據庫/上下文中看到一個配置文件,所以它創建表並向其中插入新記錄?我可以告訴它不要這樣做嗎?用戶和圖像存儲在兩個不同的數據庫中。
我不介意把它們放在同一個數據庫中,但它doesn't seem to like using the DefaultContext for my images。
切換到'UserId'帶走了相當多的便利 - 然後我必須手動執行所有抓取操作,不是嗎?我想我會不管,因爲它無法處理跨數據庫連接? 「你可以在GalleryContext數據庫上創建UserProfile的物化視圖」是什麼意思? – mpen
@Mark Single'DbContext'只能用於一個數據庫。你提到兩個表位於不同的數據庫中。因此,爲了在一個上下文中使用它們(例如,連接,導航等等),你可以在'GalleryContext'數據庫中創建'Profile'表。 – Eranga
正如問題中提到的那樣,它們也是獨立的'DbContexts',儘管..'UserContext'和'GalleryContext'。我不確定「創建視圖」是什麼意思,我想我對MS SQL並不熟悉,但無論如何,我已經設法將所有內容都放到一個數據庫中,只有一個'DbContext',並且發生同樣的問題。它仍然創建額外的配置文件。我可以明白爲什麼它會這樣做,如果'Profile.UserId'爲'0'或'null',但它設置正確,那麼它爲什麼試圖創建更多而不是僅僅鏈接它? – mpen