Reputation: 282845
Every time I upload a new image and link it with a Profile, it also creates a new Profile in the wrong database.
I imagine it's created via this code:
var imageMeta = new ImageMeta
{
Name = imageForm.Name,
User = Profile,
};
...
db.Images.Add(imageMeta);
db.SaveChanges();
Where Profile
comes from my 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;
}
}
}
That method, Profile.get
, pulls the correct Profile for the logged-in user from the UsersContext
, but the db
in the first snippet is actually a GalleryContext
.
I'm guessing it doesn't see a profile in that database/context, so it's creating the table and inserting new records into it? Can I tell it not to do that? The users and images are simply stored in two different databases.
I wouldn't mind putting them in the same database, but it doesn't seem to like using the DefaultContext for my images.
Upvotes: 1
Views: 172
Reputation: 32437
If your ImageMeta
and UserProfile
belong to two separate databases, you have few options.
Instead of having a UserProfile
type User
property in ImageMeta
class, you can provide a scalar property 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; }
}
Then the ImageMeta
insertion looks like
var imageMeta = new ImageMeta
{
Name = imageForm.Name,
UserId = Profile.Id,
};
...
db.Images.Add(imageMeta);
db.SaveChanges();
You can create a materialized view of UserProfile
on GalleryContext
database. Then both contexts will use the same table. After that you can detach the Profile
instance from UsersContext
and attach it to GalleryContext
when saving ImageMeta
.
Upvotes: 2