我已经尝试了 StackOverflow 中的几乎所有方法来防止这些错误。我不知道我做错了什么。当我开始进行一些更改以删除一个错误时,会出现第二个错误,反之亦然。我不知道它是否连接到数据库,或者它是否可以初始化数据库,或者不能。看起来我的数据库文件是空的 - 我正在使用 SQLite,我想使用 EF 的 Code First 机制。
我的代码
using System.Data.Entity;
using ControlCenter;
namespace ControlCenter
{
public class IncomingMessaggesContext: DbContext
{
public DbSet<UnifiedPositionMessage> UnifiedPositionMessages { get; set; }
public DbSet<MessageDescription> MessageDescriptions { get; set; }
static IncomingMessaggesContext()
{
Database.SetInitializer<IncomingMessaggesContext>(null);
}
}
}
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ControlCenter.CommunicationGateway
{
using System;
using TrackingDevices.Positioning;
public class UnifiedPositionMessage
{
public int Id { get; set; }
public uint DeviceID { get; set; }
public DateTime ReceiveTime { get; set; }
public PositionBase DevicePosition { get; set; }
public object UserPayload { get; set; }
public int MessageDescriptionId { get; set; }
[ForeignKey("Id")]
[Required]
public virtual MessageDescription MessageDescription { get; set; }
}
public class MessageDescription
{
public int Id { get; set; }
public bool IsMessageValid { get; set; }
public virtual UnifiedPositionMessage UnifiedPositionMessage { get; set; }
}
}
调用数据库
using (var db = new IncomingMessaggesContext() )
{
var msgDesc = new MessageDescription() {IsMessageValid = true, Id = 0, UnifiedPositionMessage = e.Frame};
db.MessageDescriptions.Add(msgDesc);
db.UnifiedPositionMessages.Add(e.Frame);
db.SaveChanges();
}
和连接设置
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<connectionStrings>
<add name="IncomingMessaggesContext"
connectionString="Data Source=c:\temp\Messages.db;"
providerName="System.Data.SQLite" />
</connectionStrings>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<system.data>
<DbProviderFactories>
<add name="SQLite Data Provider"
invariant="System.Data.SQLite"
description="Data Provider for SQLite"
type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
</configuration>