简体   繁体   中英

EF 4.2 Create a relation one-to-one without relationship on the Database

I need to rewrite a classic ASP to C#.NET and the system have 2 tables:

Table 1:

Table1
{
   [Key]
   public string WebRef {get;set;}
   ....
}

Table 2:

 Table2
{
  [Key]
  public string WebRef{get;set;}
  [Key]
  public int sequence{get;set;}
   .....
}

On the SQL Server they don't have any relation but It's one-to-one relationship.

Question: Is it possible to create a relationship using EF 4.2?

I need to put the table 2 inside the model of table 1 to be like:

Table1
{
   [Key]
   public string WebRef {get;set;}
   ....
   public Table2 table2{get;set}
}

Thank you in advance.

Try this

public class Table1
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOptions.Identity)]
    public int Table1ID{get;set;}

}

public class Table2
{
     [Key]
     [DatabaseGenerated(DatabaseGeneratedOptions.Identity)]
     public int Table2ID{get;set;}

     [ForeignKey("Table1")]
     public int Table1ID {get;set;}

     public virtual Table1 Table1 {get; set;}

}

This is a One-to-N relationship, to make a One-to-One relationship, you need to set Table1ID of Table2 as UniqueKey by SQLSERVER, because EF CodeFirst does not support unique keys...

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