我有一个使用 Entity Framework 6.1 Code First 创建的数据库,我有一个特定的表有问题。
我有一个名为Manifests的表,下面是实体定义
public class Manifest
{
public int Id { get; set; }
public DateTime ReleaseDate { get; set; }
public int VersionMajor { get; set; }
public int VersionMinor { get; set; }
public int VersionBuild { get; set; }
public int VersionRevision { get; set; }
public Version Version
{
get
{
return new Version(this.VersionMajor, this.VersionMinor, this.VersionBuild, this.VersionRevision);
}
set
{
this.VersionMajor = value.Major;
this.VersionMinor = value.Minor;
this.VersionBuild = value.Build;
this.VersionRevision = value.Revision;
}
}
public string ReleaseNotes { get; set; }
public bool IsCompulsory { get; set; }
public string Description { get; set; }
public string UpdatePackage { get; set; }
}
您会注意到我定义了一个属性,它是一个 System.Version
并将存储 list 版本,但是,当我在包管理器控制台中运行 add-migration 时,生成的迁移不包括 Version
柱子。我试过设置 modelBuilder.ComplexType<System.Version>()
在 OnModelCreating
但无济于事,请帮忙?
按照建议我已经更改了实体定义(见上文),但我现在在运行种子时遇到错误,请见下文:
System.Data.Entity.Core.EntityCommandCompilationException: An error occurred while preparing the command definition. See the inner exception for details. ---> System.Data.Entity.Core.MappingException:
(6,10) : error 3004: Problem in mapping fragments starting at line 6:No mapping specified for properties Manifest.Version in Set Manifests.
An Entity with Key (PK) will not round-trip when:
Entity is type [Drogo.Meera.Data.Context.Manifest]
种子方法有以下内容:
context.Manifests.AddOrUpdate(
p => p.Version,
new Manifest
{
Description = "Initial Release",
VersionMajor = 1,
VersionMinor = 0,
VersionBuild = 0,
IsCompulsory = true,
ReleaseDate = DateTime.Now,
ReleaseNotes = "Initial Release",
UpdatePackage = @"v1-0-0\v1-0-0.zip"
});
context.SaveChanges();
最佳答案
我认为当您将 System.Version
用作复杂类型时,您没有看到预期的结果,因为它没有可供 EF 使用的任何有效属性。
If a property has only a getter or a setter, but not both, it will not be included in the model.
您应该能够通过提取您想要自己保留的属性(并将 Manifest.Version
标记为要忽略的属性)来解决此问题。
public class Manifest
{
// other properties
int VersionMajor { get; set; }
int VersionMinor { get; set; }
int VersionBuild { get; set; }
int VersionRevision { get; set; }
public Version Version
{
get
{
return new Version(VersionMajor, VersionMinor, VersionBuild, VersionRevision);
}
set
{
VersionMajor = value.Major;
VersionMinor = value.Minor;
VersionBuild = value.Build;
VersionRevision = value.Revision;
}
}
}
// Adding [NotMapped] to Manifest.Version would also work, as in the link below
modelBuilder.Entity<Manifest>().Ignore(m => m.Version);
这里还有另一个例子:Entity Framework map multiple columns to C# complex type
关于c# - 使用 Entity Framework Code First 在数据库中存储 System.Version,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31662534/