我们有一个现有的数据库和一个脚本,可以接收电子邮件,找到我们想要的数据(即名称,地址,电子邮件等),然后将数据作为字段/值对插入数据库( “FieldLabel”和“FieldValue”的列。
我现在正在实现一个API(WCF服务)来使用C#和Entity Framework替换此电子邮件解析。我正在创建一个DataContract,“Details”,其中包含传递给API的“Name”,“Address”,“Email”等DataMemebers。然后我有一个InsertData()方法,我想用它来获取每个数据成员并使用它的名称作为FieldLabel,它的值作为FieldValue。
例如,使用Name =“Brian”和ZipCode =“11111”,我想创建Name / Brian&的标签/值对。邮编/ 11111。
以下是我在伪代码中的用法:
DetailsTable _detail = new DetailsTable(); // EF table object
foreach (datamemeber in Details)
{
_detail.FieldLabel = datamemeber.toString();
_detail.FieldValue = datamember.Value();
}
更新:添加了我的详情DataContract的代码
[DataContract]
public class Details
{
public LeadDetail()
{
FirstName = "";
LastName = "";
StreetAddress = "";
City = "";
State = "";
ZipCode = "";
}
public LeadDetail(string firstName, string lastName, string streetAddress,
string city, string state, string zipCode)
{
FirstName = firstName;
LastName = lastName;
StreetAddress = streetAddress;
City = city;
State = state;
ZipCode = zipCode;
}
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
[DataMember]
public string StreetAddress;
[DataMember]
public string City;
[DataMember]
public string State;
[DataMember]
public string ZipCode;
}
答案 0 :(得分:1)
为了使您的伪代码工作,需要解决一些问题。首先,您需要遍历实例化的Details对象的字段以检索键/值对,然后从DetailsEntity创建实体以执行插入。如果我理解您的问题正确区分详细信息的名称(用户名,zip,...)和DetailsKeyValue(FieldLabel,FieldValue)类将提高您的代码的可理解性。
以下代码将遍历Details对象的字段并插入等效的EF实体DetailsKeyValue。
using (var context = new DetailsKeyValueContext()) {
foreach (FieldInfo field in details.GetType().GetFields()) {
var detailsKeyValue = new DetailsKeyValue();
detailsKeyValue.FieldLabel = field.Name;
detailsKeyValue.FieldValue = field.GetValue(details) as string;
context.DetailsKeyValue.Add(detailsKeyValue);
}
context.SaveChanges();
}
以下是代码第一个实体和上下文类。
public class Details
{
public string Name;
public string Zip;
public string Email;
}
public class DetailsKeyValue
{
public string FieldLabel { get; set; }
public string FieldValue { get; set; }
}
public class DetailsKeyValueContext: DbContext
{
public DbSet<DetailsKeyValue> DetailsKeyValue { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<DetailsKeyValue>()
.HasKey(x => x.FieldLabel);
}
}
答案 1 :(得分:0)
你的'伪代码'看起来与实际代码几乎相同。你需要的只是一个围绕它的DbContext,一个与你的上下文同名的连接字符串(例如DetailsContext),你准备好了。
<强>编辑:强>
Details details = Populate(); // Populated from parameter passed in
using (var context = new DetailsContext())
{
DetailsEntity _detail = new DetailsEntity(); // EF table object
foreach (datamemeber in details)
{
_detail.FieldLabel = datamemeber.Type;
_detail.FieldValue = datamember.Value;
}
context.SaveChanges();
}