![](/img/trans.png)
[英]Entity Framework Fluent API relationship mapping HasRequired().WithRequired() not behaving correctly without Map()
[英]Entity framework WithRequired fluent api to data annotations mapping
我正在嘗試在我的代碼優先實體框架項目中使用數據注釋方法。
這是我的實體:(顯示有限的字段)
public partial class CUSTOMEREXT
{
[StringLength(36)]
public string ID { get; set; }
public virtual CUSTOMER CUSTOMER { get; set; }
}
public partial class CUSTOMER
{
[StringLength(36)]
public string ID { get; set; }
public virtual CUSTOMEREXT CUSTOMEREXT { get; set; }
}
Fluent API:(這有效)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CUSTOMER>()
.Property(e => e.ID)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<CUSTOMER>()
.HasOptional(e => e.CUSTOMEREXT)
.WithRequired(e => e.CUSTOMER);
modelBuilder.Entity<CUSTOMEREXT>()
.Property(e => e.ID)
.IsFixedLength()
.IsUnicode(false);
}
動態生成模型構建器:(這不起作用)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.AddFromAssembly(Assembly.GetAssembly(GetType())); //Current Assembly
base.OnModelCreating(modelBuilder);
}
測試代碼:
Model1 model = new Model1();
var outp = model.Set<CUSTOMEREXT>().ToList();
var out1p = model.Set<CUSTOMER>().ToList();
錯誤:
無法確定類型“OraclePOC.CUSTOMER”和“OraclePOC.CUSTOMEREXT”之間關聯的主體端。 必須使用關系流暢 API 或數據注釋顯式配置此關聯的主體端。
通過查看這個,我知道我必須將WithRequired
轉換為數據注釋屬性。 不確定如何?
任何的想法?
我能夠弄清楚這一點:
添加[Required]
屬性:
public partial class CUSTOMEREXT
{
[StringLength(36)]
public string ID { get; set; }
[Required]
public virtual CUSTOMER CUSTOMER { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.