简体   繁体   中英

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)

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'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

By looking at this , I know I have to convert WithRequired to data annotation attribute. Not sure How?

Any idea?

I was able to figure this out:

Add [Required] attribute:

public partial class CUSTOMEREXT
{
    [StringLength(36)]
    public string ID { get; set; }

    [Required]
    public virtual CUSTOMER CUSTOMER { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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