gpt4 book ai didi

c# - EF4.1 : How to deal with items being added to an Object's collection

转载 作者:太空宇宙 更新时间:2023-11-03 14:16:38 25 4
gpt4 key购买 nike

我是第一次使用 EF4.1(请耐心等待),但我无法掌握如何将新项目添加到对象的子集合,然后保存该对象。

例如,对于下面的类,我最初可以将 TravelTicket(包含多个人)保存到我的数据库中,但是当我添加一个新人然后再次尝试保存 TravelTicket 时,我得到:

ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象。

有人能帮忙吗?

public class TravelTicket
{
public int Id { get; set; }
public string Destination { get; set; }
public virtual List<Person> Members { get; set; }
}

public class Person
{
public int Id { get; set; }
public string Name{ get; set; }
}

编辑:所有相关代码按要求添加:

领域模型:

public class TravelTicket
{
public int Id { get; set; }
public string Destination { get; set; }
public virtual ICollection<Person> Members { get; set; }
}

public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}

数据库上下文:

public class TicketContext : DbContext
{
public TicketContext()
: base("TicketStore")
{ }

public DbSet<TravelTicket> TravelTickets { get; set; }
public DbSet<Person> People { get; set; }
}

存储库(仅相关方法):

public class TicketRepository : ITicketRepository
{

TicketContext context = new TicketContext();

public void InsertOrUpdate(TravelTicket quoteContainer)
{
if (quoteContainer.Id == default(int))
{
// New entity
context.TravelTickets.Add(quoteContainer);
}
else
{
// Existing entity
context.Entry(quoteContainer).State = EntityState.Modified;
}
}

public void Save()
{
try
{
context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
}

public interface ITicketRepository
{
void InsertOrUpdate(TravelTicket travelTicket);
void Save();
}

消费(示例)MVC Controller 代码:

public class TicketSaleController : Controller
{
private readonly ITicketRepository ticketRepository;

public TicketSaleController()
: this(new TicketRepository())
{
}

public TicketSaleController(ITicketRepository ticketRepository)
{
this.ticketRepository = ticketRepository;
}

public ActionResult Index()
{
TravelTicket ticket = new TravelTicket();
ticket.Destination = "USA";
List<Person> travellers = new List<Person>();
travellers.Add(new Person { Name = "Tom" });
travellers.Add(new Person { Name = "Dick" });
travellers.Add(new Person { Name = "Harry" });
ticket.Members = travellers;

ticketRepository.InsertOrUpdate(ticket);
ticketRepository.Save();

Session["Ticket"] = ticket;
return RedirectToAction("Next");
}

public ActionResult Next()
{
TravelTicket ticket = (TravelTicket)Session["Ticket"];
ticket.Members.Add(new Person { Name = "Peter" });
ticket.Members.Add(new Person { Name = "Paul" });
ticketRepository.InsertOrUpdate(ticket);
ticketRepository.Save();
return View();
}
}

调用“ticketRepository.InsertOrUpdate(ticket);”在“Next”方法上导致异常:

ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象。

进一步编辑:如果我在保存对象后从数据库中拉回对象而不是从 session 中拉取对象,则添加 2 个新人可以正常工作:

作品: TravelTicket ticket = ticketRepository.Find(ticketId); ticket.Members.Add(new Person { Name = "Peter"}); ticket.Members.Add(new Person { Name = "Paul"}); ticketRepository.InsertOrUpdate(ticket); ticketRepository.Save();

不起作用: TravelTicket ticket = (TravelTicket)Session["Ticket"]; ticket.Members.Add(new Person { Name = "Peter"}); ticket.Members.Add(new Person { Name = "Paul"}); ticketRepository.InsertOrUpdate(ticket); ticketRepository.Save();

最佳答案

我需要查看您用来添加项目的代码,然后保存它们。直到那几个通用的建议。

看起来您正在使用长期存在的上下文来做您的事情。使用短暂的生活环境是一个很好的做法,就像这样:

  • 实例上下文
  • 做一个单一的操作
  • 处理上下文

冲洗并重复您必须执行的每项操作。在遵循这一良好做法的同时,您可能会间接解决您的问题。

同样,如需更具体的帮助,请发布您正在使用的代码;)

关于c# - EF4.1 : How to deal with items being added to an Object's collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6425983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com