如何在Fluent API中声明一对多,以便不需要它? [英] How to declare a one-to-many in Fluent API so that it's not required?

查看:128
本文介绍了如何在Fluent API中声明一对多,以便不需要它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Donkey 
{
public Guid Id {得到;组; }
}

class Monkey
{
public Guid Id {get;组; }
public Donkey Donkey {get;组;
}

我可以配置关系如下。

  protected override void OnModelCreating(DbModelBuilder model)
{
base.OnModelCreating(model);
model.HasDefaultSchema(dbo);
...
model.Entity< Monkey>
.HasRequired(_ => _.Donkey)
.WithMany()
.Map(_ => _.MapKey(DonkeyId));
}

我想让它不需要,即这样>驴属性可以是 null ,但如果不是,它指向该表中的一行。



不知道是否可能,因为作为FK依赖其目标是一个PK,这不可能是空的。但是,在C#中,这将是完美的。我可以有一个没有附件的自由运行的猴子(因为它的驴是 null ),但是我也可以分配一个驴,我想要EF和导航属性为我取得魔法。 p>

可以实现吗?

解决方案

您可以使用 HasOptional:

  model.Entity< Monkey> 
.HasOptional(_ => _.Donkey)
.WithMany()
.Map(_ => _.MapKey(DonkeyId));


Suppose we have the two classes below.

class Donkey
{
  public Guid Id { get; set; }
}

class Monkey
{
  public Guid Id { get; set; }
  public Donkey Donkey { get; set; }  
}

I can configure the relation as follows.

protected override void OnModelCreating(DbModelBuilder model)
{
  base.OnModelCreating(model);
  model.HasDefaultSchema("dbo");
  ...
  model.Entity<Monkey>
    .HasRequired(_ => _.Donkey)
    .WithMany()
    .Map(_ => _.MapKey("DonkeyId"));
}

I'd like to make it not-required, i.e. so that Donkey property can be null but if it isn't, it's pointing to a row in that table.

I'm not sure if it's possible because that being a FK relies on its target to be a PK, which can't be null ever. However, in C#, it'd make a perfect sense. I can have a freely running monkey with no attachments (since its donkey is null) but I also can assign a donkey to it and I want EF and navigational properties to do the fetching magic for me.

Is it possible to achieve?

解决方案

You can use HasOptional:

  model.Entity<Monkey>
    .HasOptional(_ => _.Donkey)
    .WithMany()
    .Map(_ => _.MapKey("DonkeyId"));

这篇关于如何在Fluent API中声明一对多,以便不需要它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆