1

この方法で自分自身を参照する必要がある 4 つの POCO オブジェクトのセットがあります。

フリーランサーは複数のクライアントを持つことができます

クライアントは複数のプロジェクトを持つことができます

プロジェクトは複数のストーリーを持つことができます。

これが可能であることを確認したいのは、フリーランサーがクライアントなしで開始し、クライアントがプロジェクトなしで開始し、プロジェクトがストーリーなしで開始することです。

ストーリーにはプロジェクトが必要であり、プロジェクトにはクライアントが必要であり、クライアントにはフリーランサーが必要です。

これが発生する関係であることを確認するために、モデル (onModelCreating オーバーライド) を作成するときに何かする必要があるかどうかを確認したいだけです。

ここに私のオブジェクトがあります:

public class Freelancer
{
    public int ID { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string CompanyName { get; set; }
    public string Avatar { get; set; }
    public Address FreelancerAddress { get; set; }
    public ICollection<Client> Clients { get; set; }
}


public class Client
{
    public int ID { get; set; }
    public string Name { get; set; }
    public Address ClientAddress { get; set; }
    public string Logo { get; set; }
    public ICollection<Project> Projects { get; set; }
}


public class Project
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Summary { get; set; }
    public string Description { get; set; }
    public ICollection<Story> Stories { get; set; }
}


 public class Story
{
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    public decimal Duration { get; set; }
    public bool Billable { get; set; }
    public string Notes { get; set; }
}

私は EF が自動的にいくつかのことを行うことを理解しています. ありがとう

4

1 に答える 1

1

慣例により、モデルはオプションの関係 (「クライアントはフリーランサーを持つことができますが、その必要はない」)を作成しますが、必須の関係 (「クライアントはフリーランサーが必要」) が必要なため、Fluent API で定義する必要があります。

modelBuilder.Entity<Freelancer>()
    .HasMany(f => f.Clients)
    .WithRequired()
    .Map(m => m.MapKey("FreelancerID"));  // FK column name in Clients table

最後の行 ( Map) がなくても作業できます。次に、EF はデフォルトの外部キー名を作成しますFreelancer_ID

他の関係についても同じマッピングです。

または、外部キー プロパティを使用して逆ナビゲーション プロパティを導入することもできます。

public class Client
{
    public int ID { get; set; }
    //...
    public ICollection<Project> Projects { get; set; }

    public int FreelancerID { get; set; }
    public Freelancer Freelancer { get; set; }
}

FreelancerIDこのようなモデルでは、外部キー プロパティが null 可能ではなく、Fluent API を使用した追加のマッピングが必要ないため、EF は必要な関係を自動的に認識します。

于 2012-09-23T17:27:13.077 に答える