简体   繁体   中英

mapping between two tables using EF Core Code first

I am looking to try to build the schema and relation between below two models using EF Core code first like below

public class Status
{
    public int Id { get; set; }
    public string Status { get; set; }
}

public class Order
{
    public Guid Id  { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public Status status { get; set; }
}

Could any one please suggest is there any changes need to be done to the above models (Status & Order) to get the query results like below

     OrderID    description    status
       1            test1      approved
       2            test2      rejected

Make your navigation property "Status" to virtual property like:

public class Status
{
    public int Id { get; set; }
    public string Status { get; set; }
}

public class Order
{
    public Guid Id  { get; set; }
    public string Name { get; set; }
    public string Description { get; set; } 
    public int StatusId { get; set; }
    public virtual Status status { get; set; }
} 

Then you can do Order.Status.Status for each row while displaying

I write code below and get next results.

1d7336aa-c144-4ca4-d2de-08d76cae93ab Description approved

public static void Main()
{
    ShowData(AddData());
}

public static void ShowData(Guid orderId)
{
    using var context = new OrderContext();
    Console.WriteLine(context.Orders
        .Where(x => x.Id == orderId)
        .First()
        .ToString());
}

public static Guid AddData()
{
    using var context = new OrderContext();
    var status = new Status()
    {
        StatusName = "approved"
    };
    var order = new Order()
    {
        Description = "Description",
        Name = "Name",
        OrderStatus = status
    };

    context.Orders.Add(order);

    context.SaveChanges();

    return order.Id;
}

public class Status
{
    public int Id { get; set; }
    public string StatusName { get; set; }

    public override string ToString()
    {
        return $"{StatusName}";
    }
}

public class Order
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual Status OrderStatus { get; set; }

    public override string ToString()
    {
        return $"{Id} {Description} {OrderStatus}";
    }
}

I think you shoudn't change anything except adding virtual modificatitor to OrderStatus.

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