LINQ: Read an Excel file and then writing to database
I am taking rows from an Excel file using LinqToExcel and then writing to SQLServer using LINQToSQL. It DID create records in the database but with null values. I wonder if I need to map the Mac object(linqtoexcel) to the HSD_TELE_INSTALLs object? I don't think I am too far off since it inserted records. Relevant code is below. Thanks in advance.
//LINQ
var macs = from x in excel.Worksheet<Mac>(sheet)
select x;
//ITERATE WITH LINQ RESULTS
foreach (var x in macs)
{
HSD_TELE_INSTALL myRecord = new HSD_TELE_INSTALL();
db.HSD_TELE_INSTALLs.InsertOnSubmit(myRecord);
db.SubmitChanges();
}
public class Mac
{
public string REGION { get; set; }
public string MACID { get; set; }
public string HOUSEKEY { get; set; }
public string HOUSENUM { get; set; }
public string STREET { get; set; }
public string UNIT { get; set; }
public string ADDRESS2 { get; set; }
public string COMMUNITY { get; set; }
public string STATE { get; set; }
public string ZIPCODE { get; set; }
public string TECHNICIAN { get; set; }
public string JOBNO { get; set; }
public string JOBTYPE { get; set; }
public string CLOSEDATE { get; set; }
public stri开发者_运维百科ng CLOSETIME { get; set; }
public string COMMENTS { get; set; }
public string MGT { get; set; }
public string COMPLETIONCODE { get; set; }
public string TCRSN { get; set; }
You're creating a new uninitialized object of type HSD_TELE_INSTALL
and then you're submitting it to DB.
You should initialize it somehow from x
. Something like:
HSD_TELE_INSTALL myRecord = new HSD_TELE_INSTALL(){SomeField=x.SomeField /*etc...*/ };
db.HSD_TELE_INSTALLs.InsertOnSubmit(myRecord);
db.SubmitChanges();
精彩评论