0

I have following entity class called Code. It stores categories of different kinds - the data for which I would have otherwise needed to create many small tables e.g. User Categories, Expense Categories, Address types, User Types, file formats etc.

public class Code
{
    public int Id { get; set; }
    public string CodeType { get; set; }
    public string CodeDescription { get; set; }


    public virtual ICollection<Expense> Expenses { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
                   :
                   : // many more

}

The class Expense looks like this:

public class Expense
{
    public int Id { get; set; }

    public int CategoryId { get; set; }
    public virtual Code Category { get; set; }

    public int SourceId { get; set; }

    public double Amount { get; set; }
    public DateTime ExpenseDate { get; set; }
}

With the above class definitions, I have established 1:many relation between Code and Expense using the CategoryId mapping.

My problem is, I want to map the SourceId field in Expense to the Code object. Which means, Expense object would contain

public Code Source { get; set; }

If I use this, at runtime I get an error about cyclic dependencies.

Can someone please help?

4

1 回答 1

0

You will need to disable cascading delete on at least one of the two relationships (or both). EF enables cascading delete by convention for both relationships because both are required since the foreign key properties are not nullable. But SQL Server doesn't accept multiple cascading delete paths onto the same table that are introduced by the two relationships. That's the reason for your exception.

You must override the convention with Fluent API:

public class Code
{
    public int Id { get; set; }
    //...
    public virtual ICollection<Expense> Expenses { get; set; }
    //...
}

public class Expense
{
    public int Id { get; set; }

    public int CategoryId { get; set; }
    public virtual Code Category { get; set; }

    public int SourceId { get; set; }
    public virtual Code Source { get; set; }
    //...
}

Mapping with Fluent API;

modelBuilder.Entity<Expense>()
    .HasRequired(e => e.Category)
    .WithMany(c => c.Expenses)
    .HasForeignKey(e => e.CategoryId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Expense>()
    .HasRequired(e => e.Source)
    .WithMany()
    .HasForeignKey(e => e.SourceId)
    .WillCascadeOnDelete(false);
于 2012-11-03T19:37:18.547 回答