如何使用Entity Framework访问与模型相关的属性?

时间:2015-10-13 12:50:31

标签: c# asp.net asp.net-mvc entity-framework asp.net-identity

我正在开发一个简单的应用程序,允许用户创建配置文件并上传多个图像。我正在使用ASP.NET Identity,因此将“user”称为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之间的一对多关系。运行应用程序后,我注意到Entity Framework在Images表中创建了ApplicationUser_id(我假设我可以将其用作外键,而不必取消注释Image域模型中的代码)。 />我还有ViewImagesViewModel,它会返回到一个视图,一组图像,我希望能够按ApplicationUser的名字,姓氏和城市进行过滤和排序。我的问题是我不知道如何将两个域模型的属性组合成一个视图模型。


问题

  1. 返回ApplicationUser时如何访问或返回Image的属性?
  2. 如何将Image的相关属性(例如ApplicationUser的{​​{1}}}绑定到UserFirstName

2 个答案:

答案 0 :(得分:2)

要将所需数据“急切地”加载到一个模型中,您可以使用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。见this MSDN article

答案 1 :(得分:1)

如你所说,你有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; }
}

以下是如何将域实体映射到viewmodel,在控制器操作中就像这样做

...
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);
}
...