如何使用实体框架访问与模型相关的属性

本文关键字:属性 模型 何使用 实体 框架 访问 | 更新日期: 2023-09-27 18:17:22

我正在开发一个简单的应用程序,允许用户创建一个配置文件并上传多个图像。我用的是ASP。NET身份,因此将"用户"称为ApplicationUser。我有一个ImageApplicationUser域模型,如下所示:

    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
        public string UserFirstName { get; set; }
        public string UserSurname { get; set; }
        public string City { get; set; }
        public virtual ICollection<Image> Image { get; set; }
    }

    public class Image
    {
        public int ImageID { get; set; }
        public string ImageCaption { get; set; }
        public int NumOfLikes { get; set; }
        public string ImageFilePath { get; set; }
        //[ForeignKey("ApplicationUser")]
        //public int ApplicationUserID { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
    }

我添加了public virtual ICollection<Image> Image { get; set; }public virtual ApplicationUser ApplicationUser { get; set; }来定义ApplicationUserImage之间的一对多关系。在运行应用程序后,我注意到实体框架已经在Images表中创建了ApplicationUser_id(我假设我可以将其用作外键,而不必取消Image域模型中的代码注释)。

我也有ViewImagesViewModel,这将返回到一个视图,图像的集合,我希望能够过滤和排序ApplicationUser的名字,姓氏和城市。我的问题是,我不知道如何从两个领域模型的属性组合成一个单一的视图模型。


  1. 当返回Image时,如何访问或返回ApplicationUser的属性?
  2. 如何绑定Image的相关属性,如ApplicationUserUserFirstNameViewImagesViewModel ?

如何使用实体框架访问与模型相关的属性

要将所需的数据'急切加载'到一个模型中,您可以使用Include

获取图片时,还可以获取用户:

var image = context.Images.Include(i => i.ApplicationUser).FirstOrDefault(i => i.ImageId == imageId);

或相反,当获取用户时,您可以获取该用户的所有图像:

var user = context.ApplicationUser.Include(u => u.Image).FirstOrDefault(u => u.Id == userId);

之后,可以访问image.ApplicationUser.UserSurname。查看这篇MSDN文章

你说你有一个ViewImagesViewModel,所以我认为这个视图模型应该是这样的

public class ViewImagesViewModel 
{
    public void ViewImagesViewModel() 
    {
        this.Images = new List<ViewImageViewModel>();
    }
    public string UserFirstName { get; set; }
    public string UserSurname { get; set; } 
    public string City { get; set; }
    public List<ViewImageViewModel> Images { get; set; }
}
public class ViewImageViewModel
{
    public string ImageUrl { get; set; }
    public int Likes { get; set; }
    public string Caption { get; set; }
}

和下面是如何将域实体映射到视图模型的,在控制器动作中这样做

...
var entity = db.ApplicationUsers.FirstOrDefault(x => x.Id == 1);
if (entity != null) 
{
    var model = new ViewImagesViewModel();
    model.UserFirstName = entity.UserFirstName;
    model.UserSurname = entity.UserSurname;
    model.City = entity.City;
    // fix the Image property in the ApplicationUser entity to be Images instead of Image as it represent a collection
    foreach (var img in entity.Images)
    {
        var imgModel = new ViewImageViewModel()
        {
            // you may change this to get the correct Url
            ImageUrl = string.Concat(HttpContext.Request.Url.Scheme, 
                  "://", HttpContext.Request.Url.Host, 
                  HostingEnvironment.ApplicationVirtualPath,
                  img.ImageFilePath),
            Likes = img.NumOfLikes,
            Caption = img.Caption
        };
        model.Images.Add(imgModel);
    }
    return View(model);
}
...