如何使用Linq to SQL重新获取数据?

时间:2016-06-14 22:19:59

标签: c# linq

Linq to SQL非常方便但是如何使用相同的DataContext对象重新获取数据?

例如,我有一个Location表,我编写了一个自定义DataContect类来检索其数据。修改其记录后,有没有办法获取原始数据而不创建另一个DataContect对象?

[Table]
class Location
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int Id { get; set; }
    [Column]
    public string Place { get; set; }

    public override string ToString()
    {
        return "[" + Id + "] " + Place;
    }
}

[Database]
class Database : DataContext
{
    public Database() : base(ConfigurationManager.ConnectionStrings["AppConnection"].ConnectionString)
    {
    }

    public Table<Location> Locations;
}

static void Main(string[] args)
{
    Database db = new Database();
    foreach(var l in db.Locations)
    {
        Console.WriteLine(l);
    }

    // Modify the first record
    var location = db.Locations.First();
    location.Place = "City Hall";

    // How do I retrieve original data before modification?
    var newList = db.Locations;
    foreach (var l in newList)
    {
        Console.WriteLine(l);
    }
}

0 个答案:

没有答案