c# - How to set up fluent API relationship in zero to zero or one to one relationship -


i beginner in asp.net mvc , entity framework. , stuck @ setting type of relationship using fluent api.

so, have 2 models:

model a

public class {     [key]     public int aid {get; set;}     public string aname {get;set;} } 

model b

public class b {    [key]    public int bid {get; set;}    public string bname } 

business logic:

  1. a can exist independently
  2. b can exist independently

  3. but during scenario example let's when when user enter "2" in textbox in ui. in scenario, want have bid stored in it.

  4. once bid started existing in table a, cannot exist again in table a.

now reason want set relationship when bid getting stored in table, need sure not random integer. want promise bid getting stored in table exist in b table.

my thinking:

i need optional unique foreign key relationship. not sure how achieve in codefirst fluent api approach

below have till now.

model a

public class {     [key]     public int aid {get; set;}     public string aname {get;set;}     public int bid {get;set;}     public virtual b {get;set;} } 

question 1: how make sure when ever bid in table, must pk present in b table question 2: type of entity relatioship dealing with? 1..0 or 1..1 or else?

edit

i want like:

dbmodelbuilder.entity<a>()                     .hasoptional(r=> r.b)                      ........ 

no need explicitly configure this. make a's fk property nullable , conventions create mapping want. eg:

public class {     public int aid { get; set; }     public string name { get; set; }     public int? bid { get; set; }     public virtual b b { get; set; } }  public class b {     public int bid { get; set; }     public string name { get; set; } } 

to in fluent api like:

        modelbuilder.entity<a>()             .hasoptional(a => a.b)             .withmany()             .hasforeignkey(a => a.bid); 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -