2

私は LINQ to DB (linq2db) を使用しており、次のような Customer プロパティを持つクラス Activity.cs があります。

public Customer Customer { get; set; }

顧客クラス:

    public class Customer
{
    [PrimaryKey, Identity]
    [Column(Name = "CustomerId"), NotNull]
    public string Id { get; set; }

    [Column(Name = "Name")]
    public string Name { get; set; }
}

今、私はこのようなことができるようにしたい:

db.Activities.First().Customer.Name  //Returns the customer name of an activity

上記で説明したように、エンティティ間の関係を設定するにはどうすればよいですか?

(はい、Id フィールドを文字列として使用する意味がないことはわかっています。乱雑なレガシー Access データベースに対して作業する必要があります)

4

2 に答える 2

2

私がよく理解していれば、1つActivityは1つを持っていCustomerます。その場合は、Activityクラスにリレーションを追加する必要があります。

[Table( Name = "Customers" )]
public class Customer
{
    [PrimaryKey, Identity]
    [Column(Name = "CustomerId"), NotNull]
    public string Id { get; set; }

    [Column(Name = "Name")]
    public string Name { get; set; }
}

[Table( Name = "Activities" )]
public class Activity
{
    [PrimaryKey, Identity]
    [Column(Name = "ActivityId"), NotNull]
    public string Id { get; set; }

    [Column( Name = "Customer" )] 
    private int? customerId; 

    private EntityRef<Customer> _customer = new EntityRef<Customer>( );

    [Association(IsForeignKey = true, Storage = "_customer", ThisKey = "customerId" )]
    public Customer Customer{
        get { return _customer.Entity; }
        set { _customer.Entity = value; }
    }
}

このテーマに関する良い記事

編集:

関連付けが機能しない場合のウォークアラウンド:

[Table( Name = "Activities" )]
public class Activity
{
    [PrimaryKey, Identity]
    [Column(Name = "ActivityId"), NotNull]
    public string Id { get; set; }

    [Column( Name = "CustomerId" )] 
    public int? CustomerId; 

}

次のようなアクティビティから顧客を取得できます。

var activity = db.Activities.FirstOrDefault()
var customer = db.Customers.FirstOrDefault(c => c.Id = activity.CustomerId);
于 2015-03-18T12:04:55.007 に答える