RaraituL RaraituL - 3 months ago 35
C# Question

HasForeignKey relationship through a Complex Type property

I have two complex types:

public class ProductItemIdentifier
{
public Guid Product_Id { get; set; }
public string ItemName { get; set; }
}

public class AuctionItemIdentifier
{
public Guid Auction_Id { get; set; }
public string ItemName { get; set; }
}


I have a entity type:

public class Comment
{
public Guid Id { get; set; }
public string Comment { get; set; }

public ProductItemIdentifier ProductItem { get; set; }
public AuctionItemIdentifier AuctionItem { get; set; }

#region Navigation

public virtual Product Product { get; protected set; }
public virtual Auction Auction { get; protected set; }

#endregion
}


And here is the
Configuration


public class CommentConfiguration : EntityTypeConfiguration<Comment>
{
HasKey(p => p.Id);

HasOptional(p => p.Product).WithMany().HasForeignKey(p => p.ProductItem.Product_Id).WillCascadeOnDelete(false);
HasOptional(p => p.Auction).WithMany().HasForeignKey(p => new { p.AuctionItem.Auction_Id }).WillCascadeOnDelete(false);
}


Basically i am trying to create a foreign key through a Complex Type property (and doesn't work).

The error i get is:

The properties expression 'p => p.ProductItem.Product_Id' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.


Is there any way to create the relationship without adding the Foreign Key columns to the
Comment
entity directly?

Answer

It's not possible. The exception has said that explicitly.

The expression should represent a property: C#: 't => t.MyProperty'

It has to be a simple property.

public class Comment
{
    ...

    public Guid Product_Id { get; protected set; } // simple property
    public virtual Product Product { get; protected set; }
}

Configuration.

HasOptional(p => p.Product)
    .WithMany()
    .HasForeignKey(p => p.Product_Id) // satisfies the C#: 't => t.MyProperty'
    .WillCascadeOnDelete(false);

And marking the ProductItemIdentifier class with [ComplexType] won't help either.

Comments