我目前正在开发一个客户项目,我必须在sqlite数据库中存储来自实体的数据。我正在使用EF6,我选择了“代码优先”方法。
问题:我想将地理坐标(Boo
中的单个点和Loo
中的点列表)存储为数据库中的System.Drawing.PointF
。因为它不是一种原始类型,遗憾的是它不像我教的那样工作。
问题:我必须在我的实体定义和/或模型配置中更改哪些内容以存储Boo
的单个点以及数据库中Loo
的点列表?提前谢谢!
我的实体课程:
public class Collection
{
[Key]
public int Id { get; set; }
public virtual List<Foo> Foos { get; set; }
}
public class Foo
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual Collection FooCollection;
}
public class Boo : Foo
{
public PointF Location { get; set; }
}
public class Loo : Foo
{
public List<PointF> Line { get; set; }
}
我的模型配置:
public class ModelConfiguration
{
public static void Configure(DbModelBuilder modelBuilder)
{
ConfigureFooCollectionEntity(modelBuilder);
}
private static void ConfigureFooCollectionEntity(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Collection>().ToTable("base.MyTable")
.HasRequired(t => t.Foos)
.WithMany()
.WillCascadeOnDelete(false);
}
private static void ConfigureGridElementEntity(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>()
.HasRequired(p => p.FooCollection)
.WithMany(fooCollection => fooCollection.Foos)
.WillCascadeOnDelete(true);
}
}
我的DbContext:
public class DbContext : DbContext
{
public DbSet<Collection> DataCollection { get; set; }
public DbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
Configure();
}
public DbContext(DbConnection connection, bool contextOwnsConnection)
: base(connection, contextOwnsConnection)
{
Configure();
}
private void Configure()
{
Configuration.ProxyCreationEnabled = true;
Configuration.LazyLoadingEnabled = true;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
ModelConfiguration.Configure(modelBuilder);
var initializer = new DbInitializer(modelBuilder);
Database.SetInitializer(initializer);
}
}
我的DbInitializer:
class DbInitializer :
SqliteDropCreateDatabaseWhenModelChanges<DbContext>
{
public GDbInitializer(DbModelBuilder modelBuilder)
: base(modelBuilder, typeof(CustomHistory))
{ }
}
答案 0 :(得分:0)
解决此问题的最简单方法是不使用System.Drawing.PointF
,而是使用自己的点类型。通过这种方式,您可以为其提供ID属性,EF可以将其存储为单独的数据库表。
这就是我的工作方式:
[TypeConverter(typeof(ExpandableObjectConverter))]
public class GeoPoint
{
[Key]
public int Id { get; set; }
public float X { get; set; }
public float Y { get; set; }
[NotMapped]
public PointF GetPointF { get { return new PointF(X, Y); } }
public GeoPoint()
{
X = 0; Y = 0;
}
public GeoPoint(float x, float y)
{
X = x; Y = y;
}
public GeoPoint(PointF point)
{
X = point.X;
Y = point.Y;
}
}