我正试图找出在Linq2Sql中保存简单的一对多关系的最佳方法。

让我们假设我们有以下POCO模型(pseduo代码顺便说一句):

人有零到多个Vechicles。

class Person
{
    IList<Vehicle> Vehicle;
}

class Vehicle
{
    string Name;
    string Colour;
}

现在,当我保存一个Person时,我将该poco对象传递给存储库代码(恰好是L2S)。我可以保存人物对象。我经常这样做。

using (Db db = new Db())
{
    var newPerson = db.People.SingleOrDefault(p => p.Id == person.Id) ?? new SqlContext.Person();
    // Left to right stuff.
    newPerson.Name = person.Name;
    newPerson.Age = person.Age;

    if (newPerson.Id <= 0)
        db.People.InsertOnSubmit(newPerson);
    db.SubmitChanges();
}

我不知道我应该在哪里以及如何处理这个人可能拥有的车辆清单?有什么建议吗?

有帮助吗?

解决方案

using (Db db = new Db())
{
    var newPerson = db.People.SingleOrDefault(p => p.Id == person.Id) ?? new SqlContext.Person();
    // Left to right stuff.
    newPerson.Name = person.Name;
    newPerson.Age = person.Age;

    // add vehicles.
    Vehicle firstV = new Vehicle();
    firstV.Name = "some name";
    firstV.Person = newPerson; // need to do this to set the person Id on the vehicle.
    newPerson.Vehicle.Add(firstV);
    // now when you save the Person it should save the Vehicle list 
    // if you set Cascade save update on the list. (not sure how to do that in L2S

    if (newPerson.Id <= 0)
        db.People.InsertOnSubmit(newPerson);
    db.SubmitChanges();
}

现在,您可以选择使用来自界面的数据构建另一级别的车辆列表。

但是你需要记住,将Vehicle添加到Person对象的列表是不够的,还需要将车辆Person属性设置为拥有车辆的人。

观察我不确定这一点,但当您执行 db.People.SingleOrDefault 时,您可能会在内存中加载整个People表。这不是你想要做的事。在评论中由Slace纠正。

其他提示

您需要做的就是确保在数据库中设置了适当的关系。

如果您的Vehicle表具有PersonId并且在将它们添加到DBML时它们之间存在外键,则Linq to SQL将检测到它们之间存在关系并创建Table<T>表示关系。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top