更新
我突然想到一个可能与这个问题相关的想法。我在这个项目中使用了代码优先的方法。最初我的ZoneMapping类就像下面你看到的那样被定义,但是数据库中只有一个PrimaryKey字段。我认为这是因为EF没有正确地解释数据。
此时,我对我的迁移SQL脚本输出进行了修改,以添加额外的主键,并将其应用于数据库。我刚才更新了迁移,而不是从下面开始:
CreateTable(
"dbo.NetC_EF_ZoneMapping",
c => new
{
PostcodeKey = c.String(nullable: false, maxLength: 128),
Zone_ID = c.Int(),
})
.PrimaryKey(t => t.PostcodeKey)
.ForeignKey("dbo.NetC_EF_Zone", t => t.Zone_ID)
.Index(t => t.Zone_ID);
我刚刚尝试在定义PostcodeKey后,在迁移中手动添加额外的PrimaryKey。
.PrimaryKey(t => t.Zone_ID)
很不幸,我仍然遇到了错误 - 我认为此迁移不用于在代码中构建EF“模型”,但我想知道它是否认为每个给定的PostcodeKey只能有一个条目,这可能解释了这种情况?
我基于Linq Except not functioning as expected - duplicate items发布了一个新问题,因为我觉得已经发现了足够的信息表明问题是无效的,实际上Except并不是问题所在。
我的问题是我有一个Linq Where子句似乎返回了错误的数据。我的数据库中的数据如下图所示:
/// <summary>
/// Represents a mapping between a postcode and a zone
/// </summary>
[Table("NetC_EF_ZoneMapping")]
public class ZoneMapping
{
/// <summary>
/// Gets or sets the postcode identifier
/// </summary>
[Key]
public String PostcodeKey { get; set; }
/// <summary>
/// Gets or sets the Zone identifier
/// </summary>
[Key]
public Zone Zone { get; set; }
}
我正在执行以下代码,它会得到不同的ID:
var result = this.context.ZoneMappings.Include("Zone").Where(z => z.Zone.ID == 257 && z.PostcodeKey == "2214");
var result2 = new FreightContext().ZoneMappings.Include("Zone").Where(z => z.Zone.ID == 257 && z.PostcodeKey == "2214");
if (result.First().Zone.ID != result2.First().Zone.ID)
throw new InvalidOperationException();
SQL(或ToString()
)对于这两个项目来说是相同的。因此,唯一的区别在于一个是新上下文,而另一个已被传递并用于其他一些内容。创建返回错误结果的上下文的代码如下:
// Copy the contents of the posted file to a memory stream
using (StreamReader sr = new StreamReader(fileUpload.PostedFile.InputStream))
using (FreightContext context = new FreightContext())
{
// Attempt to run the import
ZoneMappingCSVImporter importer = new ZoneMappingCSVImporter(sr, context, System.Globalization.CultureInfo.CurrentUICulture);
var items = importer.GetItems().ToList();
importer.SaveItems(items);
this.successBox.Value = "Import completed and added " + items.Count() + " zones mappings.";
}
这将在我使用的库中注册一个ClassMap,其中:
这样做是为了告诉库如何把XML或JSON数据解释成类对象或者把类对象转化成XML或JSON格式的数据。
public ZoneMappingCSVImporter(TextReader textReader, FreightContext context, CultureInfo culture)
: base(textReader, context, culture)
{
this.reader.Configuration.RegisterClassMap(new ZoneMappingMap(this.context));
}
我使用上下文进行查找:
/// <summary>
/// Initializes a new instance of the <see cref="ZoneMap"/> class.
/// </summary>
public ZoneMappingMap(FreightContext context)
{
if (context == null)
throw new ArgumentNullException("context");
Map(m => m.PostcodeKey);
Map(m => m.Zone).ConvertUsing(row =>
{
// Grab the name of the zone then go find this in the database
String name = row.GetField<String>("Zone");
return context.Zones.Where(z => String.Compare(z.Name, name, true) == 0).FirstOrDefault();
});
}
我看不出这里发生了任何奇怪的事情,我验证了Entity Framework生成的SQL,验证了数据库是相同的 - 我不明白为什么会返回错误的记录。有人能解释一下吗?