2012-09-05 35 views
1

每次我上传一个新的图像并将其与一个配置文件链接,它也会在错误的数据库中创建一个新的配置文件。为什么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

回答

2

如果您的ImageMetaUserProfile属于两个单独的数据库,那么您的选择很少。

而不必在ImageMetaUserProfileUser属性,你可以提供一个标量属性UserId

public class ImageMeta 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 
    public int UserId { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<ImageFile> Files { get; set; } 
} 

然后ImageMeta插入看起来像

var imageMeta = new ImageMeta 
    { 
     Name = imageForm.Name, 
     UserId = Profile.Id, 
    }; 
... 
db.Images.Add(imageMeta); 
db.SaveChanges(); 

您可以在GalleryContext数据库中创建的UserProfile物化视图。然后这两个上下文将使用同一个表。之后,您可以从UsersContext分离Profile实例,并在保存ImageMeta时将其附加到GalleryContext

+0

切换到'UserId'带走了相当多的便利 - 然后我必须手动执行所有抓取操作,不是吗?我想我会不管,因为它无法处理跨数据库连接? “你可以在GalleryContext数据库上创建UserProfile的物化视图”是什么意思? – mpen

+0

@Mark Single'DbContext'只能用于一个数据库。你提到两个表位于不同的数据库中。因此,为了在一个上下文中使用它们(例如,连接,导航等等),你可以在'GalleryContext'数据库中创建'Profile'表。 – Eranga

+0

正如问题中提到的那样,它们也是独立的'DbContexts',尽管..'UserContext'和'GalleryContext'。我不确定“创建视图”是什么意思,我想我对MS SQL并不熟悉,但无论如何,我已经设法将所有内容都放到一个数据库中,只有一个'DbContext',并且发生同样的问题。它仍然创建额外的配置文件。我可以明白为什么它会这样做,如果'Profile.UserId'为'0'或'null',但它设置正确,那么它为什么试图创建更多而不是仅仅链接它? – mpen

相关问题