简体   繁体   中英

How do I map entity framework to a child-parent look up table based on a key

I have a database that has a parent-child look up for my drop down values, there is a domain table which represents what type of drop down it is ie "TITLE", "MARITAL_STATUS", "COUNTRY" and there is look up for the values associated with each of these drop downs that we call domain values

EG TITLE (Domain table)

  • MR (Domain Value table)
  • MRS (Domain Value table)
  • MISS (Domain Value table)
  • DOCTOR (Domain Value table)

MARITAL_STATUS (Domain table)

  • SINGLE (Domain Value table)
  • MARRIED (Domain Value table)
  • DIVORCED (Domain Value table)

I find myself writing ugly code which exposes the under lying implementation similar to below

using (var db = new OrderContext())
{
    ...

    var maritalStatusId = (
                                from sp in db.DomainValues
                                where sp.ShortCode == "MARRIED"
                                where sp.Domain.ShortCode == "MARITAL_STATUS"
                                select sp.Id
                            ).FirstOrDefault();

    if maritalStatusId != 0)
    {
        orderStore.maritalStatus = maritalStatusId;
    }

    ...

    db.OrderStores.Add(orderStore);
    db.SaveChanges();
}

Is it possible to write code that looks similar to this

using (var db = new OrderContext())
{
    ...

    orderStore.maritalStatus = new MaritalStatus { ShortCode = "MARRIED" }

    ...

    db.OrderStores.Add(orderStore);
    db.SaveChanges();
}

, where a navigation property handles the insert?

If so how do I set this up?

Any links to articles on this would be good too.

You can keep a cache with the different values of your dropdowns, that seems reasonnable, or you can use enumeration if the values are not dynamic.

Another solution would be to have the shortcode field to be the primary key of the table, all your problems would be resolved.

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