![](/img/trans.png)
[英]How do I set the absolute path for a assembly containing Database connector? MySQL Connector 6.4.3 with Entity Framework 4.1
[英]How do I access a MySQL database with Entity Framework
背景:我已經創建了一個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; }
}
}
您需要使用連接器-http://dev.mysql.com/downloads/connector/net
也使用連接器重新生成模型。
我自己弄清楚了。 您需要將連接字符串添加到app.config文件中,然后安裝Entity Framework Power Tools,然后使用它對數據庫中的模型進行反向工程。
創建連接字符串時,請確保將Persist Security Info = True設置為True
我遇到的另一個問題是Visual Studios一直嘗試使用連接器的6.6.5版本,而不是安裝的版本6.7.4。
所以我也必須將此行添加到app.config文件中
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.6.5.0" newVersion="6.7.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.