MapleStory MapleStory - 2 months ago 34
ASP.NET (C#) Question

EF: one to one relationship without generate new column using fluent API

every time I tried to add-migration and then it shows me the code like this:

public override void Up()
{
AddColumn("dbo.Orders", "OrderItems_Id", c => c.Int(nullable: false));
CreateIndex("dbo.Orders", "OrderItems_Id");
AddForeignKey("dbo.Orders", "OrderItems_Id", "dbo.OrderItems", "Id");
}


I seek the google and haven't found the solution,my entity belows,I want to set the OrderId of orderItems as a foreign key references by Orders.

public class OrderItems
{
public int Id { get; set; }
public int OrderId {get; set;}
public virtual Orders Order { get; set; }
}
public class Orders
{
public int Id { get; set; }

public virtual OrderItems Order { get; set; }
}


My Fluent API looks like belows:

public OrderItemsMapping()
{
this.HasKey(x => x.Id);
this.Property(x => x.GoodId).IsRequired();
this.Property(x => x.OrderId).IsRequired();
this.Property(x => x.Price).IsRequired();
this.Property(x => x.Quantity).IsRequired();
this.Property(x => x.Score).IsRequired();

this.HasOptional(x => x.Order)
.WithOptionalPrincipal(x => x.OrderItems)
.Map(configurationAction: new Action<ForeignKeyAssociationMappingConfiguration>(x => x.MapKey()));

}


another things I have to be mentioned is that x.MapKey("Id") will trigger error :Name had been set and it must be unique. thanks.

Answer

You have said that, there is one-to-one relationship between Order and OrderItem entities. If this is the case, then OrderId must be primary key in the OrderItem entity.

Also, your entity's names shouldbe named in singular rather than plural by convention.

As a result, your entities must look like:

public class OrderItem
{
    public int OrderId { get; set;}

    public virtual Order Order { get; set; }
}

public class Order
{
    public int Id { get; set; }

    public virtual OrderItem OrderItem { get; set; }
}

And OrderItem mapping:

// Primary Key
this.HasKey(m => m.OrderId);

...
this.HasRequired(m => m.Order)
    .WithRequiredDependent(m => m.OrderItem);
...
Comments