我在identityModel类中向ApplicationUser添加了一个属性,以便像这样扩展它
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();
}
}
这是指用户可以拥有多个帖子的事实。我的Post.cs类看起来像这样
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);
}
问题在于&#34; posts.appUser.Id&#34;当我尝试保存到数据库时,字段始终评估为null。我该怎么办?
答案 0 :(得分:0)
您的ApplicationUser
关系没有明确的外键属性,因此仅将其与Post
一起保存是从数据库中查找用户并设置appUser
属性那个。
在这方面,你在这里遇到了一些严重的问题,因为看起来你正试图混合并匹配Identity和ASP.NET Membership。它们是两个完全不同的系统,彼此不兼容。要从数据库中获取与当前经过身份验证的用户相对应的ApplicationUser
实例,您需要执行以下操作:
var user = UserManager.GetById(User.Identity.GetUserId());
所有Membership.*
系列方法都不适用。