在添加实体类的集合属性时苦苦挣扎。我一直收到以下错误:
来自'User_ProfilePic'AssociationSet的关系在 '添加'状态。给定多重约束,相应的 'User_ProfilePic_Source'也必须处于'已添加'状态。
以下是用于将图像保存到数据库的方法:
public void SaveImage(Library library, Image image)
{
image.PostedBy = new User { Id = image.PostedBy.Id, ProfilePic = new ProfilePic { Id = image.PostedBy.ProfilePic.Id} };
var lib = Libraries.FirstOrDefault(l => l.Id == library.Id);
lib.Images.Add(image);
// context.Entry(lib).State = EntityState.Unchanged;
context.Entry(image.PostedBy).State = EntityState.Unchanged;
// context.Entry(image.PostedBy.ProfilePic).State = EntityState.Unchanged;
context.SaveChanges();
}
(我一直在尝试使用这种方法一段时间试图让它工作,所以你可以看到它看起来有点“玩”了)
以下是有用的相关课程:
public class Image : EntityBase
{
public string Url { get; set; }
public User PostedBy { get; set; }
}
public class User
{
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ProfilePic ProfilePic { get; set; }
}
public class Library
{
public List<Image> Images { get; set; }
}
public class ProfilePic : Image
{
// public int ProfilePicId { get; set; }
public string Test { get; set; }
}
public class Image : EntityBase
{
public string Url { get; set; }
public User PostedBy { get; set; }
public List<Thumbnail> Thumbnails { get; set; }
}
public abstract class EntityBase
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateAdded { get; set; }
public EntityBase()
{
DateAdded = DateTime.Now;
}
}
编辑:
public IQueryable<Image> Images
{
get { return context.Images; }
}
public IQueryable<Library> Libraries
{
get { return context.Libraries.Include("Images").Include("Documents"); }
}
public IQueryable<User> Users
{
get { return context.Users.Include("ProfilePic"); }
}
任何人都可以推荐如何通过这个?提前谢谢。