【问题标题】:Store data in LINQ to two tables; Join LINQ将 LINQ 中的数据存储到两个表中;加入 LINQ
【发布时间】:2013-07-23 18:08:40
【问题描述】:

我在 MVC4 中使用 simplemembership,效果很好,但是我需要添加其他用户详细信息,例如名字和姓氏、电子邮件、国家/地区,每个用户可以有多个配置文件,所以我从用户表中添加 ID {FK}在 UserProfile 表中。 用户注册时我有单独的表格,系统调用另一个表格询问附加详细信息。我正在使用代码优先现有数据库方法

我错过了如何存储附加信息以及使用 LINQ 对其用户配置文件进行存储的难题。

提前非常感谢..

数据库:

CREATE TABLE [dbo].[UserProfile] (
[UserId]   INT            IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (150) NOT NULL,
[ID]       INT            NOT NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC),
FOREIGN KEY ([ID]) REFERENCES [dbo].[Users] ([ID])
);

CREATE TABLE [dbo].[Users] (
[ID]         INT            IDENTITY (1, 1) NOT NULL,
[Email]      NVARCHAR (150) NOT NULL,
[First_Name] NVARCHAR (150) NOT NULL,
[Last_Name]  NVARCHAR (150) NOT NULL,
[Country]    NVARCHAR (150) NOT NULL,
PRIMARY KEY CLUSTERED ([ID] ASC)
);

控制器类

  [HttpGet]
    [Authorize]
    public ActionResult UserDetail()
    {

        return View();
    }

    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public ActionResult UserDetail(User model)
    {

        using (var db = new DB5Context_01())
        {
            var user_info = new User
            {
                First_Name = model.First_Name,
                Last_Name = model.Last_Name,
                Country = model.Country,
                Email = model.Email
            };

           //// need help here ??? hock Userprofile with User

        }

SimpleMemberShip 初始化

namespace Simple_LoginSystem_05.Filters
{
public class InitializeSimpleMembership : ActionFilterAttribute
{
    public InitializeSimpleMembership()
    {
        try
        {
            if (!WebSecurity.Initialized)
            {
                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            }
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
        }
    }
}
}

型号

  public partial class User
{
    public User()
    {
        this.UserProfiles = new HashSet<UserProfile>();
    }

    public int ID { get; set; }
    public string Email { get; set; }
    public string First_Name { get; set; }
    public string Last_Name { get; set; }
    public string Country { get; set; }

    public virtual ICollection<UserProfile> UserProfiles { get; set; }

【问题讨论】:

  • 你的表名是不是混淆了?不可能是对的
  • 我猜不是...我说的是每个用户可以有许多 UserProfile,但每个 UserProfile 属于一个用户
  • 只需创建一个 List 并为属于该用户的每个 UserProfile 填写它
  • 如果我提出正确的问题,我该如何做 LINQ 部分
  • @toxic,很难理解你的问题部分是“一边说 hocking its user profile”,你能编辑一下吗?

标签: c# linq simplemembership


【解决方案1】:

SimpleMembership 期望每个用户有一个“UserProfile”,它存储在您在调用时指定的表中:

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

在默认代码中,该表名为“UserProfile”,与AccountModels.cs 中的UserProfile 匹配。有关UserProfile 的更多信息,请参阅my answer to this question 的详细信息部分4。

我还应该注意,如果不是满足您的要求“每个用户可以有多个个人资料”,那么您通常只需将电子邮件、名字、姓氏、国家/地区等属性添加到 @ 987654327@上课。我还将该类从UsersContext 移出到我自己的上下文中,删除UsersContext 并将UsersContext 中的引用更新到AccountControllerInitializeSimpleMembershipAttribute 中我自己的上下文中(你甚至可以set the Email as the login token 而不是@ 987654333@ 使用这种方法)。

所以,虽然我不明白单个用户如何需要多个名字等,但假设您有充分的理由这样做,那么对于您的实例,您将不得不引入新术语,例如:

  • UserProfile - 保持这个意思是 SimpleMembership UserProfile,因为它会使文档更容易阅读。此表中每次登录都会有一条记录。
  • AttributesForUser - 我将使用它来描述您的要求“其他用户详细信息,例如名字和姓氏、电子邮件、国家/地区以及每个用户可以拥有多个个人资料的限制”。这似乎对应于您上面的User 表。为该表使用名称 User 将导致与来自成员资格的 UserWebSecurity 框架方法和属性发生冲突,因此可能不是最好的主意。 UserProfiles 表中的每个条目都可以在 AttributesForUsers 表中具有一个或多个条目。

看起来您已经对代码优先的详细信息进行了排序。您的public virtual ICollection&lt;UserProfile&gt; UserProfiles { get; set; } 示例是正确的,但您可以将其更改为:

public virtual ICollection<AttributesForUser> AttributesForUser { get; set; }

然后您的 AttributesForUser(您也将其作为 DbSet 添加到数据上下文中)将如下所示:

public class AttributesForUser
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int UserId { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string Country { get; set; }
    [Required]
    public string Email { get; set; }

    [ForeignKey("UserId")]
    public UserProfile UserProfile { get; set; }
}

创建用户后,您可以:

using (MyContextdb = new MyContext())
{
  WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
  // assumes you have moved UserProfile to MyContext, alter code accordingly if not
  UserProfile userProfile = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
  AttributesForUser newAttribs = new AttributesForUser { 
    UserId = userProfile.UserId,
    ... fill in other properties here ... 
  };
  db.AttributesForUsers.Add(newAttribs);
  // do as many more newAttribs as you need for this userId
  ...
  // and now save
  db.SaveChanges();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多