简体   繁体   中英

Entity Framework Code First - Reference same table

I am still starting with Entity Framework Code First. I want to be able to select a Resource from list when creating a new resource. How do I reference a Resource with a Resource model.

public class Resource
{

    public int ResourceId { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    [EmailAddress]
    public string EmailAddress { get; set; }
    [Required]
    public string Password { get; set; }
    public string FullName { get; set; }


    public int TimeManagerId { get; set; }

    public int TravelManagerId { get; set; }

    public int OvertimeManagerId { get; set; }

    public int AbsenceManagerId { get; set; }
    public virtual Resource TimeManager { get; set; }
    public virtual Resource TravelManager { get; set; }
    public virtual Resource OvertimeManager { get; set; }
    public virtual Resource AbsenceManager { get; set; }

}

I think you're pretty close! If you want to do this by convention, you can change the foreign keys in your model to the form of [navigation property name][principal primary key property name]. Specifically, change Id to ResourceId so it matches the primary of the table you're referencing (which happens to be itself)...

public int TimeManagerResourceId { get; set; }
public int TravelManagerResourceId { get; set; }
public int OvertimeManagerResourceId { get; set; }
public int AbsenceManagerResourceId { get; set; }

Since you're just starting with EF code first, I'd recommend you install the Entity Framework Power Tools. You'll be able to right-click on the .cs file containing your DbContext, and it'll generate a read-only diagram of the mappings.

Try it out with your current model... right-click on entity in the diagram and view Table Mappings. You'll see EF wasn't able to figure out your foreign keys and created 4 more for you. Once you make the changes above, generate the diagram again and see the difference.

Edit: Docs on code first conventions... http://msdn.microsoft.com/en-us/data/jj679962.aspx

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