C# 派生类型上的键…但它';不是
我是EF7新手,遇到了一个奇怪的问题。我有这门课:C# 派生类型上的键…但它';不是,c#,entity-framework,C#,Entity Framework,我是EF7新手,遇到了一个奇怪的问题。我有这门课: public class Site { public int ID { get; set; } public string Title { get; set; } public string HouseNumber { get; set; } public string StreetName { get; set; } public string City { get; set; } public
public class Site
{
public int ID { get; set; }
public string Title { get; set; }
public string HouseNumber { get; set; }
public string StreetName { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public DataSource Source { get; set; }
public object Parameters
{
get
{
switch( Source )
{
case DataSource.StealthStats:
return JsonConvert.DeserializeObject<StealthStatsParameters>( JSONParameters );
default:
throw new Exception( "Site::Parameters::get() - Unhandled DataSource " + Source.ToString() );
}
}
set
{
switch( Source )
{
case DataSource.StealthStats:
JSONParameters = JsonConvert.SerializeObject( value );
break;
default:
throw new Exception( "Site::Parameters::set() - Unhandled DataSource " + Source.ToString() );
}
}
}
protected string JSONParameters { get; set; }
public List<Observation> Observations { get; set; }
}
顺便说一句,如果有人能推荐一些关于EF7的好教程和解释的链接,我将不胜感激。在与EF合作多年后,我发现它的学习曲线非常陡峭,而我在网上找到的东西也没有太大帮助。我将此信息发布在github实体框架网站上,Smit Patel很快回答了这个问题并解释了发生了什么。你可以读到他当时写的东西。塔克斯,帕特尔 简短的版本是这样的:EF类中的对象属性导致创建EF迁移的代码在整个扫描中包括对象类型。由于所有类都是对象的后代,并且对象并没有固有的主键,所以所有类都会违反“只有根类才能定义键”的限制 解决方案是不将对象属性映射到基础数据库(我就是这么做的) 在这样做的过程中,我发现您似乎必须通过对属性应用[NotMapped]注释来表明您的意图。fluent API方法:
builder.Entity<T>().Ignore(t => t.PropertyToIgnore);
builder.Entity().Ignore(t=>t.propertyToIgore);
不起作用。还有一件事:如果调用HasKey(),必须先调用Ignore()。否则错误仍然存在。。。
public class Observation
{
public int SiteID { get; set; }
public DateTime TimeStamp { get; set; }
public int MPH { get; set; }
public int VehicleCount { get; set; }
public virtual Site Site { get; set; }
}
builder.Entity<T>().Ignore(t => t.PropertyToIgnore);