C# userId总是计算为null
我在identityModel类中向ApplicationUser添加了一个属性,以便像这样扩展它C# userId总是计算为null,c#,asp.net,asp.net-mvc,asp.net-identity,C#,Asp.net,Asp.net Mvc,Asp.net Identity,我在identityModel类中向ApplicationUser添加了一个属性,以便像这样扩展它 public class ApplicationUser : IdentityUser { **public ICollection<Posts> post { get; set; }** public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager&
public class ApplicationUser : IdentityUser
{
**public ICollection<Posts> post { get; set; }**
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 class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public class Posts
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid PostId { get; set; }
public string PostTitle { get; set; }
public string PostContent { get; set; }
public DateTime PostDate { get; set; }
public virtual ApplicationUser appUser { get; set; }
}
最后一行代码是指帖子属于用户这一事实。
但是,在我的帖子控制器中,我使用
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PostTitle,PostContent")] Posts posts)
{
if (ModelState.IsValid)
{
var posting = new PostVM();
posts.PostId = Guid.NewGuid();
posts.PostTitle = posting.PostTitle;
posts.PostContent = posting.PostTitle;
posts.PostDate = DateTime.Now;
var currentUser = Membership.GetUser(User.Identity.Name);
string username = currentUser.UserName; //** get UserName
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;//** get user ID
posts.appUser.Id = userGuid.ToString();
db.Post.Add(posts);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(posts);
}
问题是,当我试图保存到数据库时,“posts.appUser.Id”字段的计算结果总是为null。我能做什么?您的
ApplicationUser
关系没有明确的外键属性,因此与Post
一起保存它的唯一方法是从数据库中查找用户,并将appUser
属性设置为该属性
在这方面,您在这里遇到了一些严重的问题,因为您似乎正在尝试混合和匹配标识和ASP.NET成员资格。它们是两个完全不同的系统,彼此不兼容。要从数据库中获取与当前经过身份验证的用户对应的ApplicationUser
实例,您需要执行以下操作:
var user = UserManager.GetById(User.Identity.GetUserId());
所有
Membership.*
方法系列在此不起作用。通过使用Bind
属性,您只启用了要填充的PostTitle
和PostContent
模型的properties。所以我不明白你怎么可能期望posts.appUser.Id
会得到一些不同于null
的值?您显式地将其从模型绑定中排除,然后期望从中获得一些值?如何向ApplicationUser添加显式外键属性。我是否只是将[ForeignKey]数据注释添加到ICollection post属性?我还使用了您编写的代码,如var user=user.Identity.GetUserId();posts.appUser.Id=用户;我得到的错误是“对象引用未设置为对象的实例”。我无法使用UserManager.GetById