在asp.net身份中配置一对一关系 [英] configuring one to one relationship in asp.net identity

查看:188
本文介绍了在asp.net身份中配置一对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的ApplicationUser类。我只添加了一个新的属性----

  public class ApplicationUser:IdentityUser 
{
// public ApplicationUser()
// {
// UserProfileInfo = new UserProfileInfo {ImageSize = 0,FileName = null,ImageData = 0};
//}
public string HomeTown {get;组; }
public virtual UserProfileInfo UserProfileInfo {get;组; }

这是我的userProfileInfo类,我想保存每个用户的个人资料图片完成后注册----

  public class UserProfileInfo 
{
// [Key,ForeignKey(ApplicationUser )]
[Key]
public int Id {get;组; }
public int ImageSize {get;组; }
public string FileName {get;组; }
public byte [] ImageData {get;组; }

[ForeignKey(Id)]
public virtual ApplicationUser ApplicationUser {get;组; }
}

这是我的DbContext类-----

  public class ApplicationDbContext:IdentityDbContext< ApplicationUser> 
{
public ApplicationDbContext()
:base(DefaultConnection)
{
}

public DbSet< UserProfileInfo> UserProfileInfo {get;组; }

现在,问题是我无法配置ApplicationUser类和UserProfileInfo之间的一对一关系我已经尝试过各种方法来做,并遵循一些堆栈溢出问题,但是在我完成了我的注册表后,它说出错误------



无法确定类型CodeFirstContext.ApplicationUser和CodeFirstContext.UserProfileInfo之间的关联的主体结束。必须使用关联流畅的API或数据注释来明确配置此关联的主要结尾。



我也试图将关系放在流利的api -----

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// base.OnModelCreating(模型构建器);

////配置Id为UserProfileInfo的PK
modelBuilder.Entity< UserProfileInfo&()
.HasKey(e => e.Id);

//为UserProfileInfo配置Id为FK
modelBuilder.Entity< ApplicationUser>()
.HasOptional(s => s.UserProfileInfo)
.WithRequired ad => ad.ApplicationUser);
}

这样我也失败了。请建议我如何配置它。 p>

解决方案

你几乎在那里
首先,您可以删除属性(Key,foreignkey)上的所有注释,按照惯例,将您的列的名称为主键(并且您的关系再次与此关联)。



其次,您只需要流畅地将您的关系从一个实体映射,例如从Applicationuser到UserProfileInfo,如下所示:

 code> protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity< ApplicationUser>()
.HasOptional(c => c.UserProfileInfo)
。 WithRequired(d => d.ApplicationUser);
base.OnModelCreating(modelBuilder);
}

注意:如果您的个人资料关系是可选的,否则使用HasRequired。
如果您现在想为用户添加配置文件设置,您可以:

  var user = UserManager.FindById(User .Identity.GetUserId()); 
var up = new UserProfileInfo {ImageSize = 12};
user.UserProfileInfo = up;
UserManager.Update(user);

更多关于流畅的映射在这里: https://msdn.microsoft.com/en-us/data/hh134698.aspx



编辑:
要将UserProfileInfo分配给ApplicationUser,您可以:



1

  //通过UserManager获取用户
var user = UserManager.FindById(User.Identity.GetUserId());
//创建新的UserProfileInfo
var up = new UserProfileInfo {ImageSize = 12};
//将UserProfileInfo分配给用户,ef将会确定该信息进入相应的UserProfileInfo表
user.UserProfileInfo = up;
//通过UserManager
更新UserManager.Update(user);

或2。

  //登录用户ID 
var userId = User.Identity.GetUserId();
使用(var db = new ApplicationDbContext())
{
//从上下文获取用户
var user = db.Users.First(c => c.Id = = userId);
// new UserProfileInfo
var up = new UserProfileInfo {ImageSize = 12};'
//将UserProfileInfo分配给用户
user.UserProfileInfo = up;
//保存更改
db.SaveChanges();
}

最后,如果你想更新userprofileinfo,而不是总是创建一个新的。你可以这样做:

  //获取现有的或创建新的UserProfileInfo 
var up = user.UserProfileInfo? ?新的UserProfileInfo();
//用新值更新
up.ImageSize = 17;请注意,您不需要关心外部应用程序ApplicationUser_Id,当您分配时,EF会自动指出这一点。 UserProfileInfo到ApplicationUser。



而且:如果你绝对要在UserProfileInfo中公开ApplicationUser的外键。您可以在UserProfileInfo类中添加一个名为ApplicationUserId的属性。按照惯例,Ef理解这一点。如果您需要这个外键的不同名称,您可以使用.HasForeignKey(fk => fk.YourForeignKeyPropertyHere)来扩展流畅的映射。


this is my ApplicationUser class.I have added only one new property ----

   public class ApplicationUser : IdentityUser
   {
    //public ApplicationUser()
    //{
    //    UserProfileInfo = new UserProfileInfo { ImageSize = 0, FileName = null, ImageData = 0 };
    //}
    public string HomeTown { get; set; }
    public virtual UserProfileInfo UserProfileInfo { get; set; }

and this is my userProfileInfo class where i want to save every user's profile pic after they have completed the registration----

  public class UserProfileInfo
  { 
   // [Key, ForeignKey("ApplicationUser")]
    [Key]
    public int Id { get; set; }
    public int ImageSize { get; set; }
    public string FileName { get; set; }
    public byte[] ImageData { get; set; }

   [ForeignKey("Id")]
    public virtual ApplicationUser ApplicationUser { get; set; }
}

and this is my DbContext class -----

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfileInfo> UserProfileInfo { get; set; }

Now, the problem is that i am unable to configure one to one relationship between ApplicationUser class and UserProfileInfo class.I have tried various ways to do it and followed some stack overflow questions previosly asked But after i had completed my registration form, it states error------

Unable to determine the principal end of an association between the types 'CodeFirstContext.ApplicationUser' and 'CodeFirstContext.UserProfileInfo'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

i have also tried to put relationship with the help of fluent api-----

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       // base.OnModelCreating(modelBuilder);

        //// Configure Id as PK for UserProfileInfo class
        modelBuilder.Entity<UserProfileInfo>()
            .HasKey(e => e.Id);

        // Configure Id as FK for UserProfileInfo
        modelBuilder.Entity<ApplicationUser>()
            .HasOptional(s => s.UserProfileInfo)
            .WithRequired(ad => ad.ApplicationUser);
    }

This way i also failed.Please suggest me how to configure it.

解决方案

You are almost there. First, you can drop all annotations on your properties (Key, foreignkey), as ef by convention makes your column with name Id the primary key (and your relationships relate to this again).

Second, you only need to fluently map your relationship from one entity, for example from Applicationuser to UserProfileInfo like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ApplicationUser>()
            .HasOptional(c => c.UserProfileInfo)
            .WithRequired(d => d.ApplicationUser);
        base.OnModelCreating(modelBuilder);
    }

Note: this if your profile relationship is optional, otherwise use, HasRequired. If you now wanted to add profile settings for a user you could:

var user = UserManager.FindById(User.Identity.GetUserId());
var up = new UserProfileInfo {ImageSize = 12};
user.UserProfileInfo = up;
UserManager.Update(user);

More about ef fluent mappings here: https://msdn.microsoft.com/en-us/data/hh134698.aspx

EDIT: To Assign a UserProfileInfo to an ApplicationUser you could either:

1

// get user via UserManager
var user = UserManager.FindById(User.Identity.GetUserId());
// create new UserProfileInfo
var up = new UserProfileInfo {ImageSize = 12};
// assign UserProfileInfo to user, ef will figure out that this info goes into the corresponding UserProfileInfo table
user.UserProfileInfo = up;
// update via UserManager
UserManager.Update(user);

or 2.

// logged in user id
var userId = User.Identity.GetUserId();
using (var db = new ApplicationDbContext())
{
     // get user from context
     var user = db.Users.First(c => c.Id == userId);
     // new UserProfileInfo
     var up = new UserProfileInfo {ImageSize = 12};'
     // assign UserProfileInfo to user
     user.UserProfileInfo = up;
     // save changes
     db.SaveChanges();
 }

Lastly if you would like to update userprofileinfo instead of always creating a new one. you could do it like this:

// get existing or create new UserProfileInfo
var up = user.UserProfileInfo ?? new UserProfileInfo();
// update with new values 
up.ImageSize = 17;

Note that You dont need to care about the foreign key ApplicationUser_Id, EF figures this out itself when you assign UserProfileInfo to an ApplicationUser.

And: if you absolutely want to expose the foreign key for ApplicationUser in UserProfileInfo. you could add a property named ApplicationUserId in class UserProfileInfo. By convention Ef understands this. IF you require a different name for this foreign key you can extend your fluent mapping by using .HasForeignKey(fk=>fk.YourForeignKeyPropertyHere)

这篇关于在asp.net身份中配置一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆