C# 使用LINQ将数据插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16388166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:55:11  来源:igfitidea点击:

Insert data into database using LINQ

c#sqllinq

提问by Advers191

I wrote a very simple method. It saves data from class DayWeatherto the database. Method checks if line with that day exist in table and update her or create a new line.

我写了一个非常简单的方法。它将类DayWeather中的数据保存到数据库中。方法检查表中是否存在当天的行并更新她或创建一个新行。

I am doing it by adding new class for LINQ and move table from Server Inspector to the constructor. It generate new class WeatherTBL.

我是通过为 LINQ 添加新类并将表从 Server Inspector 移动到构造函数来实现的。它生成新类WeatherTBL

Method itself looks like this:

方法本身看起来像这样:

public static void SaveDayWeather(DayWeather day)
    {
        using (DataClassesDataContext db = new DataClassesDataContext())
        {
            var existingDay =
              (from d in db.WeatherTBL
               where d.DateTime.ToString() == day.Date.ToString()
               select d).SingleOrDefault<WeatherTBL>();
            if (existingDay != null)
            {
                existingDay.Temp = day.Temp;
                existingDay.WindSpeed = day.WindSpeed;
                existingDay.Pressure = day.Pressure;
                existingDay.Humidity = day.Humidity;
                existingDay.Cloudiness = day.Cloudiness;
                existingDay.TypeRecip = day.TypeRecip;
                db.SubmitChanges();
            }
            else
            {
                WeatherTBL newDay = new WeatherTBL();
                newDay.DateTime = day.Date;
                newDay.Temp = day.Temp;
                newDay.WindSpeed = day.WindSpeed;
                newDay.Pressure = day.Pressure;
                newDay.Humidity = day.Humidity;
                newDay.Cloudiness = day.Cloudiness;
                newDay.TypeRecip = day.TypeRecip;
                db.WeatherTBL.InsertOnSubmit(newDay);
                db.SubmitChanges();
            }
        }
    }

When I tried to call him from UnitTest project:

当我试图从 UnitTest 项目中给他打电话时:

  [TestMethod]
    public void TestDataAccess()
    {
        DayWeather day = new DayWeather(DateTime.Now);
        DataAccessClass.SaveDayWeather(day);
    }

It write, that test has passed successfully. But if look into table, it has`t chanched. No error messages shows. Does anyone know whats the problem?

它写道,该测试已成功通过。但如果查看表格,它并没有改变。没有错误消息显示。有谁知道是什么问题?

P.S. Sorry for my bad English.

PS抱歉我的英语不好。

UDPProblem was in that: "...db maybe copied to the debug or release folder at every build, overwriting your modified one". Thanks @Silvermind

UDP问题在于:“...db 可能会在每次构建时复制到调试或发布文件夹,覆盖您修改过的文件夹”。谢谢@Silvermind

回答by Arun Kumar

I wrote simple method to save employee details into Database.

我编写了简单的方法将员工详细信息保存到数据库中。

Checkout this link to know Insert, Update, Delete operations using LINQ C#

查看此链接以了解使用 LINQ C# 的插入、更新、删除操作

     private void AddNewEmployee()
     {
        using (DataContext objDataContext = new DataContext())
        {                
            Employee objEmp = new Employee();
            // fields to be insert
            objEmp.EmployeeName = "John";
            objEmp.EmployeeAge = 21;
            objEmp.EmployeeDesc = "Designer";
            objEmp.EmployeeAddress = "Northampton";                
            objDataContext.Employees.InsertOnSubmit(objEmp);
            // executes the commands to implement the changes to the database
            objDataContext.SubmitChanges();
        }
      }

Getting started with LINQ C#

开始使用 LINQ C#

回答by Pranab Kumar De

Please try with lambda expression. In your code, var existingDayis of type IQueryableIn order to insert or update, you need a variable var existingDayof WeatherTBLtype. Hence try using below..

请尝试使用 lambda 表达式。在代码中,VAR existingDay是类型的IQueryable为了插入或更新,你需要一个变量VAR existingDayWeatherTBL类型。因此尝试使用下面..

 var existingDay =
 db.WeatherTBL.SingleOrDefault(d => d.DateTime.Equals(day.Date.ToString()));

 if(existingDay != null)
  {
   //so on...
  }

Hope it should work..

希望它应该工作..

回答by Jeff.k.Daniel

Linq to SQL

LINQ 到 SQL

        Detail tc = new Detail();


        tc.Name = txtName.Text;
        tc.Contact = "92"+txtMobile.Text;
        tc.Segment = txtSegment.Text;
        var datetime = DateTime.Now;
        tc.Datetime = datetime;
        tc.RaisedBy = Global.Username;
        dc.Details.InsertOnSubmit(tc);

        try
        {


            dc.SubmitChanges();
            MessageBox.Show("Record inserted successfully!");
            txtName.Text = "";
            txtSegment.Text = "";
            txtMobile.Text = "";

        }


        catch (Exception ex)
        {
            MessageBox.Show("Record inserted Failed!");

        }