Implementacja relacji Zero lub jeden do zera lub jeden w kodzie EF najpierw przez Fluent API

Mam dwie klasy POCO

public class Order
{
  int id;
  string code;
  int? quotationId;  //it is foreign key
  public int Id{get;set;}
  public string Code{get;set;}
  public int? QuotationId{get;set;}
  Quotation quotation;
  public virtual Quotation Quotation { get; set; }
  ....
}

public class Quotation
{
  int Id;
  string Code;
  public int Id{get;set;}
  public string Code{get;set;}
  Order order;
  public virtual Order Order { get; set; }
  ....   
}

Każde zlecenie może być wykonane z jednej lub zerowej notacji, a każda notacja Może spowodować zamówienie, więc mam relację" jeden lub zero "do" jeden lub zero", Jak mogę to zaimplementować w kodzie EF najpierw przez fluent API?

Author: Masoud, 2013-02-05

5 answers

Zmieniając pocos na:

public class Order
{
    public int OrderId { get; set; }
    public virtual Quotation Quotation { get; set; }
}
public class Quotation
{
    public int QuotationId { get; set; }
    public virtual Order Order { get; set; }
}

I używając tych plików mapowania:

public class OrderMap : EntityTypeConfiguration<Order>
{
    public OrderMap()
    {
        this.HasOptional(x => x.Quotation)
            .WithOptionalPrincipal()
            .Map(x => x.MapKey("OrderId"));
    }
}

public class QuotationMap : EntityTypeConfiguration<Quotation>
{
    public QuotationMap()
    {
        this.HasOptional(x => x.Order)
            .WithOptionalPrincipal()
            .Map(x => x.MapKey("QuotationId"));
    }
}

Będziemy mieć ten DB (czyli 0..1-0..1):

Tutaj wpisz opis obrazka

Ze szczególnymi podziękowaniami dla (Pana Vahid Nasiri )

 31
Author: Masoud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-11 19:29:52

Procedura Masouds to:

modelBuilder.Entity<Order>()
            .HasOptional(o => o.Quotation)
            .WithOptionalPrincipal()
            .Map(o => o.MapKey("OrderId"));

modelBuilder.Entity<Quotation>()
            .HasOptional(o => o.Order)
            .WithOptionalPrincipal()
            .Map(o => o.MapKey("QuotationId"));

Daje:

Tutaj wpisz opis obrazka

Zmieniając kod na:

modelBuilder.Entity<Order>()
            .HasOptional(o => o.Quotation)
            .WithOptionalPrincipal(o=> o.Order);

Daje:

Tutaj wpisz opis obrazka

 19
Author: Kenneth Bo Christensen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-05 18:21:48

Zobacz http://msdn.microsoft.com/en-us/data/jj591620 relacje EF

Doskonała książka http://my.safaribooksonline.com/book/-/9781449317867

Oto post od dewelopera z grudnia 2010. Ale nadal istotne http://social.msdn.microsoft.com/Forums/uk/adonetefx/thread/aed3b3f5-c150-4131-a686-1bf547a68804 Powyższy artykuł jest miłym podsumowaniem lub możliwymi kombinacjami tutaj.

Rozwiązanie, w którym tabela zależna ma klucz z podstawowej stół jest możliwy.

Jeśli chcesz niezależnych kluczy, gdzie oba są głównymi w scenariuszu PK / FK, nie sądzę, że możesz to zrobić najpierw w kodzie z Fluent API. Jeśli mają wspólny klucz, Jesteś w porządku. 1: 1 opcjonalny zakłada, że zależny używa klucza z Primary.

Ale ponieważ musisz zapisać jedną z tabel przed drugą. Możesz sprawdzić jeden z kluczy obcych za pomocą kodu. Lub dodać drugi obcy do bazy danych po utworzeniu kodu pierwszego.

Zbliżysz się. Ale EF będzie narzekaj na sprzeczne klucze obce, jeśli chcesz, aby oba były kluczami obcymi. Zasadniczo zależy a od B zależy A EF nie lubi, nawet jeśli kolumny są nullable i technicznie możliwe NA DB.

Tutaj użyj tego programu testowego, aby go wypróbować. Po prostu skomentuj rzeczy płynne API, aby wypróbować kilka opcji. Nie mogłem zmusić EF5.0 do współpracy z niezależnym PK / FK 0:1 do 0: 1 Ale oczywiście istnieją rozsądne kompromisy, o których mowa.

using System.Data.Entity;
using System.Linq;
namespace EF_DEMO
{
class Program
{
    static void Main(string[] args) {
        var ctx = new DemoContext();
        var ord =  ctx.Orders.FirstOrDefault();
        //. DB should be there now...
    }
}
public class Order
{
public int Id {get;set;}
public string Code {get;set;}
public int? QuotationId { get; set; }   //optional  since it is nullable
public virtual Quotation Quotation { get; set; }
  //....
}
public class Quotation
{
 public int Id {get;set;}
 public string Code{get;set;}
// public int? OrderId { get; set; }   //optional  since it is nullable
 public virtual Order Order { get; set; }
 //...
}
public class DemoContext : DbContext
{
    static DemoContext()
    {
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DemoContext>());
    }
    public DemoContext()
        : base("Name=Demo") { }
    public DbSet<Order> Orders { get; set; }
    public DbSet<Quotation> Quotations { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       modelBuilder.Entity<Order>().HasKey(t => t.Id)
                    .HasOptional(t => t.Quotation)
                    .WithOptionalPrincipal(d => d.Order)
                    .Map(t => t.MapKey("OrderId"));  // declaring here  via MAP means NOT declared in POCO
        modelBuilder.Entity<Quotation>().HasKey(t => t.Id)
                    .HasOptional(q => q.Order)
            // .WithOptionalPrincipal(p => p.Quotation)  //as both Principals
            //        .WithOptionalDependent(p => p.Quotation) // as the dependent
            //         .Map(t => t.MapKey("QuotationId"));    done in POCO.
            ;
    }   
}
}
 5
Author: phil soady,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-05 13:43:11

Dopasowane z tej odpowiedz , Spróbuj tego.

Najpierw popraw swoje zajęcia:

public class Order
{
  public int Id {get; set;}
  public virtual Quotation Quotation { get; set; }
  // other properties
}

public class Quotation
{
  public int Id {get; set;}
  public virtual Order Order { get; set; }
  // other properties
}

Następnie użyj płynnego API w ten sposób:

modelBuilder.Entity<Quotation>()
.HasOptional(quote => quote.Order)
.WithRequired(order=> order.Quotation);

Zasadniczo, dla relacji 1: 1 lub [0/1]: [0/1], EF potrzebuje wspólnych kluczy podstawowych.

 4
Author: Moritz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:21
public class OfficeAssignment
{
    [Key]
    [ForeignKey("Instructor")]
    public int InstructorID { get; set; }
    [StringLength(50)]
    [Display(Name = "Office Location")]
    public string Location { get; set; }

    public virtual Instructor Instructor { get; set; }
}

Atrybut Klucza

Między instruktorem a jednostką organizacyjną istnieje relacja jeden do jednego. Przydział biurowy istnieje tylko w odniesieniu do instruktora, do którego został przydzielony, a zatem jego klucz główny jest również kluczem obcym do jednostki instruktorskiej. Jednak struktura encji nie może automatycznie rozpoznać InstructorID jako klucza podstawowego tego encji, ponieważ jej nazwa nie jest zgodna z konwencją nazw ID lub classnameID. Dlatego atrybut Key jest używany do identyfikacji go jako klucza:

Https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

 1
Author: astro8891,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-28 04:28:15