背景:我已经创建了一个 ASP.net MVC 4 应用程序和一个 mysql 数据库。我使用代码优先来生成数据库。Web App 将用作与数据交互的 UI。但是,数据是在单独的 C# 程序中创建的。它从串行设备获取测试数据。
问题: 我不知道如何在我的 c# 应用程序中使用实体框架连接到数据库。
我已经创建了一个新模型供 C# 应用程序使用。我读过使用共享的 .DLL 不是最好的主意。
这就是我到目前为止所拥有的。
private ReportDBContext db = new ReportDBContext();
private void saveReport()
{
string connStr = "server=RnD-Chopper;user=CWXDAQ;database=ReportDB;port=3306;password=QADXWC;";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
db.Reports.Add();
// Perform database operations
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Console.WriteLine("Done.");
unlockGUI();
}
报告模型
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using MySql.Data.Entity;
using MySql.Data.MySqlClient;
using System.Linq;
using System.Web;
namespace CXW__DAQ___Record.Models
{
public class Report
{
[Display(Name = "Test ID #")]
public int ID { get; set; }
[Required(ErrorMessage = "Test Name is Required")]
[Display(Name = "Test Name")]
public string Name { get; set; }
[Display(Name = "Date Tested")]
public DateTime TestDate { get; set; }
[Display(Name="Test Done For")]
public string TestFor { get; set; }
public string Comment { get; set; }
public enum enumForceUnits { lbs };
public enum enumTimeUnits { mS };
[Required(ErrorMessage = "Unit of Force (ForceUnit) is required")]
public enumForceUnits forceUnit;
[Required(ErrorMessage = "Unit of Time (TimeUnit) is required")]
public enumTimeUnits timeUnit;
public virtual ICollection<Reading> Readings { get; set; }
}
public class Reading
{
public int ID { get; set; }
public virtual Report Report { get; set; }
public long Time { get; set; }
public double Force { get; set; }
}
public class ReportDBContext : DbContext
{
public DbSet<Report> Reports { get; set; }
public DbSet<Reading> Readings { get; set; }
}
}