简体   繁体   中英

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. 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 . 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

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. Why used DataAnnotation in your class with Fluent API. Keep everything in the fluent API is a lot cleaner.

[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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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