以编程方式将行添加到Linq-to-SQL数据集 [英] Programmatically Add Row to Linq-to-SQL Dataset

查看:45
本文介绍了以编程方式将行添加到Linq-to-SQL数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们为网格生成了此链接到sql的数据集:

Let's say we generate this link-to-sql dataset for a grid:

var query = from c in customers
                    orderby c.FirstName
                    select c;

Grid1.DataSet = query;
Grid1.DataBind();

生成此数据集后,我们需要以编程方式向该数据集添加"Vince Vaughn"(目标是在此linq-to-sql数据集中添加一行,以便从数据库中获取值,以及是通过编程方式添加的,均显示在网格中.

After generating this dataset, we need to programmatically add "Vince Vaughn" to this dataset (the goal is to add a row to this linq-to-sql dataset so that the values obtained from the database, and the 1 row that was programmatically added, all appear in the grid).

如何使用C#以编程方式完成此任务?(即以编程方式将Vince Vaughn的行添加到数据集中)

How would be accomplish this programmatically using C#? (i.e. programmatically add a row for Vince Vaughn to the dataset)

CUSTOMERS TABLE
ID     FirstName    LastName    
1      John         Jones    
2      Sally        Smith

环境:C#.NET 4.0

Environment: C#.NET 4.0

谢谢.

推荐答案

如果您的意思是实际将行添加到后端存储,并且假设 ID 是一个标识列并且您的模型已正确配置你可以的.

If you mean actually add the row to the back end storage and, assuming ID is an identity column and your model is correctly configured you can do.

using (var context =  new ...)
{
    context.customers.Add(
        new Customer { FirstName = "Vince", LastName = "Vaughn" });
    context.SubmitChanges();
}

如果您只想让文斯(Vince)出现在列表中,就可以这样做

If you just want Vince to appear as if he is in the list you could do

var query = customers.Concat(new Customer[]
    { 
        new Customer
            {
                ID = customers.Max(c => c.ID) + 1,
                FirstName = "Vince",
                LastName = "Vaughn"
            }
    }).OrderBy(c => c.FirstName);

这会将Vince添加到列表中,而没有实际将其添加到存储中.

That would add Vince to the list without actually adding him to the storage.

如果您只想从数据库中欺骗"一个或多个结果,则可以与一组兼容的匿名类型相结合,诸如此类...

If you just want to "spoof" a result or results into a set from a database you could concatentate with a set of a compatible anonymous type, somthing like this ...

var queryWithVince = query.Select(r = new 
                    { 
                        FirstName = r.FirstName, 
                        LastName = r.LastName
                    })
    .Concat( new []
        {
            new { FirstName = "Vince", LastName = "Vaughn" }
        }
    .OrderBy(p => p.FirstName);

如果两个匿名类型的成员具有相同的属性名称和类型,则它们是兼容的.如果 query 的结果是其他一些非匿名类型,则需要确保linq处理能够将这些结果与您的匿名添加项结合起来.

Two anonymous types are compatible if thier members have the same property names and types. If the result of query is some other non anonymous type you'll need to ensure that the linq processing is able to combine those results with your anonymous additions.

这篇关于以编程方式将行添加到Linq-to-SQL数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆