简体   繁体   English

流利的API一对多代理

[英]Fluent API One-Or-Many to One realtionship

I'm trying to implement a One-Or-Many to One relationship with Fluent API without success for the moment. 我正在尝试通过Fluent API实现一对多关系,但暂时没有成功。 Especially on the cascade on delete that doesn't work for the moment. 尤其是在删除级联上,目前暂时不起作用。

The relationship needs to be implemented between the two classes Event and Location . 需要在两个类EventLocation之间实现该关系。 An Event has at least one Location, on the other side a Location can be attributed to different Events. 一个事件至少具有一个位置,在另一侧,一个位置可以归因于不同的事件。

EDIT: An Event has exact one Location instead of 'at least one'. 编辑:一个事件具有确切的一个位置,而不是“至少一个”。 Sorry for this. 非常遗憾。

When I delete an Event and there are no more Events using the Location in question, then the Location needs to be deleted also. 当我删除一个事件并且没有其他使用该位置的事件时,则该位置也需要删除。 As long as the Location is used by an Event, the Location still needs to be stored because it's required for an event to have one. 只要某个事件使用该位置,该位置仍需要存储,因为一个事件必须具有该位置。

Here is my code: 这是我的代码:

Fluent API 流利的API

modelBuilder.Entity<Event>()
            .HasRequired<Location>(c => c.Location)
            .WithMany();
            .WillCascadeOnDelete();

Class Event 课堂活动

[Key]
public Guid EventID { get; set; } = Guid.NewGuid();
public string Description { get; set; }
public Location Location { get; set; }

Class Location 上课地点

[Key]
public Guid LocationID { get; set; } = Guid.NewGuid();
public string Description { get; set; }

You need to modify your Location Class and modelBuilder like the below. 您需要像下面那样修改Location Class和modelBuilder。 Why used DataAnnotation in your class with Fluent API. 为什么在类中使用Fluent API使用DataAnnotation。 Keep everything in the fluent API is a lot cleaner. 将所有内容保持在流利的API中会更加干净。

[Key]
public Guid LocationID { get; set; } = Guid.NewGuid();
public string Description { get; set; }
public ICollection<Event> Events {get; set;}


modelBuilder.Entity<Event>()
        .HashMany<Location>(e = > e.Events)
        .WithRequired(l => l.Location)
        .WillCascadeOnDelete();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM