簡體   English   中英

MVC將列表保存到數據庫

[英]MVC saving a list to Database

嗨,我正在嘗試將電子郵件列表保存到數據庫中,但是我無法保存列表。

這是模型中的列表:

[Display(Name = "Mailing List")]
public List<string> MailingList { get; set; }

這是我試圖在列表中添加新的字符串電子郵件並將其保存到數據庫的控制器方法

public ActionResult VenueMailingList(int id)
{
    //Get UserID and Email
    string UserId = User.Identity.GetUserId();
    string email = User.Identity.Name;

    //Check if the user is logged in
    if (UserId != null)
    {
        ViewBag.LoggedIn = true;

        //Add the users email to this venues email mailing list
        Venue venue = db.Venues.Find(id);

        //If list is null, initlise it
        if (venue.MailingList == null)
        {
            venue.MailingList = new List<string>();
        }

        venue.MailingList.Add(email);

        db.SaveChanges();
    }
    return View();
}

您需要在DbContext內部進行數據庫更改,以便EntityFramework跟蹤更改並將這些更改保存到數據庫中。 您需要如下代碼:

using (var context = new MyDbContext())
{
     Venue venue = context.Venues.Find(id);

     //If list is null, initlise it
     if (venue.MailingList == null)
     {
          venue.MailingList = new List<string>();
     }

     venue.MailingList.Add(email);

     context.SaveChanges();
}

以下鏈接提供了有關如何使用EntityFramework的精彩教程: http ://www.entityframeworktutorial.net/EntityFramework4.3/add-entity-using-dbcontext.aspx。

嘗試這個:

if (venue.MailingList == null)
{
          venue.MailingList = new List<string>();
}

venue.MailingList.Add(email);
venue.MailingList.Entry(email).State = EntityState.Added; // you need to add this statement

db.SaveChanges();

請使用addrange方法。

db.YourTable.AddRange(YourList)
db.SaveChanges();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM