1

私は深い水の上にいると確信していますが、私は多数の「類似の」投稿を見ているように見ていますが、私はこのことを理解できないようです。Asp.net C#多対多関係EF ApplicationUser

"Company model"とApplicationUserとの接続を確立しようとしています。 会社は多くのAUを保有しており、AUは多くの企業を保有することができます。私が会社を作り、selectListから別のユーザーを選んだとき(私がチェックしたのは、AU-IDを渡します)

警告:私は新人ですない - そう明白な誤りがあるかもしれません

モデル企業:

public Company() 
    { 
     this.Users = new List<ApplicationUser>(); 
    } 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string Address { get; set; } 
    public string Zip { get; set; } 
    public string City { get; set; } 
    public string Cvr { get; set; } 
    public string Telephone { get; set; } 
    public string Email { get; set; } 
    public string Website { get; set; } 
    public string BillingEmail { get; set; } 
    [ForeignKey("UserId")] 
    public List<string> UserId { get; set; } 
    public virtual List<ApplicationUser> Users { get; set; } 
} 

モデルApplicationUser

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 
     userIdentity.AddClaim(new Claim("FirstName", this.FirstName.ToString())); 
     userIdentity.AddClaim(new Claim("LastName", this.LastName.ToString())); 
     return userIdentity; 
    } 
    public ApplicationUser() 
    { 
     this.Companies = new List<Company>(); 
    } 

    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public virtual List<Company> Companies { get; set; } 
} 
01。

コントローラ

[HttpPost] 
    public async Task<ActionResult> CreateCompany(CreateCompanyViewModel model) 
    { 

     if (ModelState.IsValid) 
     { 


      DAL.CompanyContext context = new DAL.CompanyContext(); 

      // Creating object from recieved form 
      DomainModels.Company newCompany = new DomainModels.Company(); 


      newCompany.Address = model.Address; 
      newCompany.BillingEmail = model.BillingEmail; 
      newCompany.City = model.City; 
      newCompany.Cvr = model.Cvr; 
      newCompany.Email = model.Email; 
      newCompany.Name = model.Name; 
      newCompany.Telephone = model.Telephone; 
      newCompany.Website = model.Website; 
      newCompany.Zip = model.Zip; 
      newCompany.UserId = model.SelectedApplicationUserId; 
      // adding and saving 
      context.Companies.Add(newCompany); 
      await context.SaveChangesAsync(); 

      return RedirectToAction("Index"); 
     } 
     return View(model); 

    } 

DbContext

public DbSet<Company> Companies { get; set; } 
    protected override void OnModelCreating(DbModelBuilder mb) 
    { 
     base.OnModelCreating(mb); 
     mb.Entity<Company>() 
      .HasMany(c => c.Users) 
      .WithMany(d =>d.Companies) 
      .Map(m=> 
      { 
      m.MapLeftKey("Company_ID"); 
      m.MapRightKey("ApplicationUser_Id"); 
      m.ToTable("CompanyApplicationUsers"); 
      }); 
    } 

    } 

私はおよそ本当に混乱していコンテキスト。 Googleを検索すると、OnModelCreateを作成する必要があることを示す記事がたくさんありますが、EFが自動的にこれを行うと思っていましたが、「CompanyApplicationUsers」テーブルを含むテーブルが自動的に作成されています)。

会社は毎回作成されますが、リレーショナルテーブルには何も掲載されません。

私はここでうんざりしている気がした - 私は学ぶことを望む! :)

ありがとうございました。

UPDATE 1:

私はモデルを変更し、代わりに外部キーとしてApplicationUser(ユーザー)を指します。

私は確信していますが、これは正しい方法ですが、私はまた、validationError "を受け取っている"私は、ビューから受信しているユーザーのリストをループし、ユーザーを作成し、 Context.savechanges上の1つまたは複数のエンティティの検証に失敗しました

ここでのエラーは、リストを記入するために作成したユーザーに関連しています。ユーザー名などの追加情報が必要です。実際のユーザーを作成するのではなく、関係のみが必要です。今病気のために

 [HttpPost] 
    public async Task<ActionResult> CreateCompany(CreateCompanyViewModel model) 
    { 

     if (ModelState.IsValid) 
     { 


      DAL.CompanyContext context = new DAL.CompanyContext(); 

      // Creating object from recieved form 
      DomainModels.Company newCompany = new DomainModels.Company(); 


      newCompany.Address = model.Address; 
      newCompany.BillingEmail = model.BillingEmail; 
      newCompany.City = model.City; 
      newCompany.Cvr = model.Cvr; 
      newCompany.Email = model.Email; 
      newCompany.Name = model.Name; 
      newCompany.Telephone = model.Telephone; 
      newCompany.Website = model.Website; 
      newCompany.Zip = model.Zip; 
      foreach (string i in model.SelectedApplicationUserId) 
      { 
       ApplicationUser user = new ApplicationUser(); 
       user.Id = i; 
       newCompany.Users.Add(user); 
      } 
      //newCompany.Users = model.SelectedApplicationUserId; 
      // adding and saving 
      context.Companies.Add(newCompany); 
      await context.SaveChangesAsync(); 

      return RedirectToAction("Index"); 
     } 
     return View(model); 

    } 

アップデート2

私は仕事をすることができ、多くの関係、に1を原因します。この場合、関連する各ユーザーのCompanyIDでApplicationUserを更新するだけです。 私はまだたくさんのものを作成する方法を知りたいと思います。おそらくここでやっていることのいくつかは、そこにも必要です。しかし、私はそれを把握できません。

//newCompany.Users = model.SelectedApplicationUserId; 
      // adding and saving 

      context.Companies.Add(newCompany); 
      try 
      { 
       int response = await context.SaveChangesAsync(); 
      } 
      catch(Exception exception) 
      { 

      } 

      foreach (string i in model.SelectedApplicationUserId) 
      { 
       var user = await UserManager.FindByIdAsync(i); 
       user.CompanyId = newCompany.ID; 
       IdentityResult result = await UserManager.UpdateAsync(user); 
      } 
      try 
      { 

      } 
      catch (Exception exception) 
      { 
       throw; 
      } 

      return RedirectToAction("Index"); 
     } 
     return View(model); 
+1

貴社のモデルには「public List UserId」という文字列が含まれています。それを取り除き、あなたのApplicationUsersのコレクションを使用してください。このような質問を参照してください:http://stackoverflow.com/questions/24509524/adding-many-to-many-relationship-from-applicationuser-to-custom-entity –

+0

ご意見ありがとうございます。私はコードを更新しましたが、検証エラーが発生しています。これがあなたの意図したものかどうかはわかりません。この方法はお勧めですか? リンクは似ていますが、私は新しいユーザーを作成しようとしておらず、単に2つをリレーショナル表にリンクするだけです。 – HAMY0707

答えて

1

あなたが適切に設定されたクラスでこれに似た何かをすることができる必要があります:

var userList = new List<ApplicationUser>(); 
foreach (string i in model.SelectedApplicationUserIds) 
{ 
    userList.Add(new ApplicationUser {Id = i}); 
} 

var newCompany = new Company 
{ 
    Address = model.Address; 
    BillingEmail = model.BillingEmail; 
    City = model.City; 
    // etc. 
    Users = userList 
}; 

int response = await context.SaveChangesAsync(); 

EFは自動的に連携を行います。ユーザを取得するためにUserManagerを使用する必要はありません。コンテキストから利用可能です。ユーザ。