简体   繁体   English

实体框架WithRequired fluent api 到数据注解的映射

[英]Entity framework WithRequired fluent api to data annotations mapping

I am trying to do Data Annotation approach in my code first entity framework project.我正在尝试在我的代码优先实体框架项目中使用数据注释方法。

Here are my entities: (showing limited fields)这是我的实体:(显示有限的字段)

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: (This works) 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);      
}

Dynamically generate model builder: (This does not work)动态生成模型构建器:(这不起作用)

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.AddFromAssembly(Assembly.GetAssembly(GetType())); //Current Assembly
    base.OnModelCreating(modelBuilder);
}

Code to test:测试代码:

Model1 model = new Model1();
var outp = model.Set<CUSTOMEREXT>().ToList();
var out1p = model.Set<CUSTOMER>().ToList();

Error:错误:

Unable to determine the principal end of an association between the types 'OraclePOC.CUSTOMER' and 'OraclePOC.CUSTOMEREXT'.无法确定类型“OraclePOC.CUSTOMER”和“OraclePOC.CUSTOMEREXT”之间关联的主体端。 The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.必须使用关系流畅 API 或数据注释显式配置此关联的主体端。

By looking at this , I know I have to convert WithRequired to data annotation attribute.通过查看这个,我知道我必须将WithRequired转换为数据注释属性。 Not sure How?不确定如何?

Any idea?任何的想法?

I was able to figure this out:我能够弄清楚这一点:

Add [Required] attribute:添加[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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM