EF Code First unidirectional One-To-Many with Data Annotations - entity-framework-4.1

Say I have the following POCO classes:
public class Parent
{
public int ID { get; set; }
}
public class Child
{
public int ID { get; set; }
public int MyParentID { get; set; }
[ForeignKey("MyParentID")]
public Parent MyParent { get; set; }
}
The Child.MyParent property maps to the Parent table with a one-to-many relationship, but I don't want the Parent class to be aware of the association (unidirectional). I can do this within the DbContext.OnModelCreating (or any of its equivalents) with the following:
modelBuilder.Entity<Child>()
.HasRequired(c => c.MyParent)
.WithMany()
.HasForeignKey(c => c.MyParentID);
But, I can't seem to find the same with data annotations. Is there such a thing? The ForeignKey annotation I am using seems to require bidirectionality, because it gives me the "Unable to determine the principal end of an association" exception until I add an ICollection<Child> property on the Parent class
UPDATE
This code should actually work as-is. The issue I was trying to isolate in my code didn't actually involve this setup. I've posted a new question regarding my problem here.

public class Child
{
public int ID { get; set; }
[ForeignKey("Parent")]
public int ParentID { get; set; }
public Parent Parent { get; set; }
}
should work. Actually you don't need to do anything - neither in Fluent API nor with annotations - because EF conventions will exactly create the relationship automatically you have defined in Fluent API. The foreign key will be detected because it has the name pattern [Navigation property]Id, the relationship will be "required" because the FK is non-nullable and it will be one-to-many because you have a single reference (Parent) on one side and "many" on the other side is default if there is no corresponding navigation property.

Related

EF - how to prevent eager loading to load all nested entities

I've manay-to-many relationship between two entities: Categories <--> Items
public class CategoryMaster
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual List<SubCategoryMaster> SubCategories { get; set; }
public List<ItemMaster> Items { get; set; }
}
public class ItemMaster
{
public long Id { get; set; }
public string Name { get; set; }
public List<CategoryMaster> Categories { get; set; }
}
Whenever I try to explicit load related items to all/certain categories, it gives me
all related items
related categories to those items
related items to those categories and so on...nested/circular references
db.CategoryMaster
.Include(x=>x.Items)
.Include(x=>x.SubCategories.Select(y=>y.Items))
.ToList();
Hence results in below error while serializing it to JSON on *.cshtml with Json.Encode();
A circular reference was detected while serializing an object of type 'GoGreen.Data.Entities.SubCategoryMaster'.
Since I've disabled the lazy loading at property level, I'm not expecting it to load all nested entities(circular references) at any point of time. Is there a way to load all related level one records i.e. Categories and related items.
Related question - But Iodon't want to go with any of the two ways suggested.
NOTE : I'm more interested in knowing why EF behaves like this. It seems a bug to me.
First approach: you can add attribute above properties you don't want to exclude it from being serialized using [ScriptIgnore], you can create partial class and add your customization if your entities are auto generated
Second approach: Create a Model with only properties you need in your view and select only this model and set your properties
EFcontext.Tabel.include(x=>x...).Select(x=>new MyModel { ... });
One workaround, and please don't kill me :-) After object loading and before serializing, just set the loaded objects which are causing the circular reference to null. I tried it and worked like a charm.
use meta data redirection. figured I would help anyone who stumbled here.
[MetadataType(typeof(CategoryMasterMetadata))]
public partial class CategoryMaster
{
}
public class CategoryMasterMetadata
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
public virtual List<SubCategoryMaster> SubCategories { get; set; }
public List<ItemMaster> Items { get; set; }
}

Entity Framework Code First: FOREIGN KEY constraint may cause cycles or multiple cascade paths

Entity Framework Code First can generate the DB for the following POCOs.
public class Item {
public int Id { get; set; }
public string Name { get; set; }
}
public class ItemPair {
public int Id { get; set; }
public virtual Item FirstItem { get; set; }
public virtual Item SecondItem { get; set; }
}
I would like to establish the relationship with First and Second item via ID fields rather than the an entire "Item" class. So:
public class ItemPair {
public int Id { get; set; }
public virtual Item FirstItem { get; set; }
public int FirstItem_Id { get; set; }
public virtual Item SecondItem { get; set; }
public int SecondItem_Id { get; set; }
}
also works. Edit: This didn't actually work. Just generates additional FirstItem_Id1 and SecontItem_Id2 columns.
But just changing the foreign key properties to FirstItemId, SecondItemId, (without the underscore) like so:
public class ItemPair {
public int Id { get; set; }
public virtual Item FirstItem { get; set; }
public int FirstItemId { get; set; }
public virtual Item SecondItem { get; set; }
public int SecondItemId { get; set; }
}
results in the following exception.
{"Introducing FOREIGN KEY constraint 'ItemPair_SecondItem' on table 'ItemPair' may cause
cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION,
or modify other FOREIGN KEY constraints.\r\nCould not create constraint.
See previous errors."}
Why? And what can I do to avoid this exception.
I decided to just remove the cascade delete convention.
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
The reasons are:
I prefer to mark records deleted or deactivated for audit purposes.
At most I delete just the junction / mapping tables.
With an ORM It is relatively trivial to loop through and delete child records in the rare case I need to.
Thank you Ladislav Mrnka pointing me in the right direction.
My expectation is that in the first case your Id properties are not used in the database as FKs and EF will create another two columns (you can validate this by forcing pairing of navigation property with FK property using ForeignKeyAttribute). In the second case EF will correctly recognize your properties but it will also use cascade delete convention which will cause error in SQL server. You have two properties from the table pointing to the same parent. Actually in the database you can createItemPair from the same Item (both FKs set to the same Id). If both relations have cascade delete enabled it will result in multiple cascade paths => not allowed in SQL server.
The solution here is fluent mapping to manually define how the relations are mapped. Here is the example.

Entity Framework 4.1 Code First, One-to-One with one table joining to a single key field of of composite key

I'm just beginning with EF4.1 Code First, and I pretty like it.
Here's the story :
A Codif class is composed of a key from a Domaine class, an Entite class, and Reference class, and a fourth field which is some text.
Reference and Codif have an one-to-one relationship.
Thing is, when it creates the Database, it creates some ugly fields in my Reference entity, creating duplicate fields of the Codif Entity.
Good point : When I manipulate my Reference object however, I have the expected behaviour of accessing the Codif property, and the duplicate fields are invisible.
Here's the code :
public class Reference
{
public int ReferenceId { get; set; }
public string Libelle { get; set; }
public virtual Codif Codif { get; set; }
}
public class Domaine
{
public int DomaineId { get; set; }
public string Libelle { get; set; }
}
public class Codif
{
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int DomaineId { get; set; }
[InverseProperty("DomaineId")]
public virtual Domaine Domaine { get; set; }
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int EntiteId { get; set; }
[InverseProperty("EntiteId")]
public virtual Entite Entite { get; set; }
[Key, Column(Order = 2)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ReferenceId { get; set; }
[InverseProperty("ReferenceId")]
public virtual Reference Reference { get; set; }
[Key, Column(Order = 3)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Codification { get; set; }
}
public class Entite
{
public int EntiteId { get; set; }
public string Nom { get; set; }
public string Email { get; set; }
}
And here's the result in the tables (images) :
Codif
Reference
In the Reference class, how can I specify that ReferenceId is the foreign key to be used against a SINGLE field of Codif ?
How to get rid of those duplicate fields in Reference ?
How to remove the Reference_ReferenceId in Codif table while preserving the navigation property ?
Thank you for your support.
Marc
Edit : I'm working with an SQL Compact Edition 4 database
Replace all your [InverseProperty("xxx")] attributes by [ForeignKey("xxx")]. I think that this is what you actually want. [InverseProperty] refers to the navigation property on the other side of the relationship which can never be a scalar property.
Edit
You could in addition to the FK attribute set the [InverseProperty] attribute on the Reference property in your Codif class:
public class Codif
{
//...
[Key, Column(Order = 2)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ReferenceId { get; set; }
[ForeignKey("ReferenceId")]
[InverseProperty("Codif")] // <-- refers to Codif property in Reference class
public virtual Reference Reference { get; set; }
//...
}
But it think it's not really necessary because EF should detect the correct relationship between Reference and Codif by convention. (I'm not sure though for one-to-one relationships.)
Edit
Problems!
First: As far as I can see you must specify the one-to-one relationship in Fluent API because EF cannot determine otherwise what's the principal and what's the dependent:
modelBuilder.Entity<Reference>()
.HasOptional(c => c.Codif)
.WithRequired(c => c.Reference);
Second: EF will still complain because of the composed key or because ReferenceId is not the key alone. If ReferenceId were the only key in Codif it would work.
Edit
I'm trying to understand what you want to achieve. Apparently your composed key in Codif is supposed to ensure that any combination of the four field values can exist only once. But this conflicts with the one-to-one relationship imo, for example this would be valid table entries:
Table Codif:
DomaineId EntiteId ReferenceId Codification
----------------------------------------------------
1 1 1 "A"
2 1 1 "A"
1 2 1 "A"
1 1 2 "A"
1 1 1 "B"
etc...
But as you can see: You can have multiple rows with the same ReferenceId which means that you cannot have a one-to-one relationship to Reference. Here you have 4 Codif entities which refer to the same Reference entity with Id = 1.
Now, I guess, the fact that you want to have a one-to-one relationship means that there is an additional constraint so that ReferenceId in Codif table can occur only once. In other words: The rows 2, 3 and 5 in the example above are invalid from business viewpoint (although valid from DB viewpoint).
If this is the case I would actually make ReferenceId the single key in Codif and make sure from business logic that the other combinations of values in the DB are unique (Query if exists before you insert a new Codif). On database side you could create a unique index over the other three fields to ensure that the combinations are always unique in the database. EF cannot check this internally though since unique constraints are not yet supported.

One To Many Relationship - Cascading Delete

I'm using EF 4.1 where I'm trying to map my POCO to my existing database. This is working fine until I try to delete an item that the other item has a dependency to. I want to enable cascading deletes, so that when my first item is deleted all dependencies would also be deleted (I believe this is called cascading delete).
I tried to enable this in the OnModelCreating:
modelBuilder.Entity<Component>()
.HasMany(c => c.Specifications)
.WithRequired(s => s.Component)
.Map(m => m.MapKey("ComponentId"))
.WillCascadeOnDelete(true);
However, I still get the The DELETE statement conflicted with the REFERENCE constraint exception.
The database is quite simple:
Component:
ComponentId (PK)
Description
Specification:
SpecificationID (PK)
Description
ComponentID (FK)
I've created the two following classes to match this setup:
public class Specification
{
[Key]
[Required]
public int Id { get; set; }
[MaxLength(50)]
[Required]
public string Description { get; set; }
public virtual Component Component { get; set; }
}
and
public class Component
{
[Key]
[Required]
public int Id { get; set; }
[MaxLength(50)]
[Required]
public string Description { get; set; }
public virtual ICollection<Specification> Specifications { get; set; }
}
Cascading delete in your model requires cascading delete in your DB. If you let the EF recreate the DB for you, it will set this up automatically. If you cannot let the EF do this, then you must either:
Add cascading delete to the FK manually, or
Remove the cascade from the model.

Applying Domain Model on top of Linq2Sql entities

I am trying to practice the model first approach and I am putting together a domain model. My requirement is pretty simple: UserSession can have multiple ShoppingCartItems.
I should start off by saying that I am going to apply the domain model interfaces to Linq2Sql generated entities (using partial classes). My requirement translates into three database tables (UserSession, Product, ShoppingCartItem where ProductId and UserSessionId are foreign keys in the ShoppingCartItem table). Linq2Sql generates these entities for me. I know I shouldn't even be dealing with the database at this point but I think it is important to mention.
The aggregate root is UserSession as a ShoppingCartItem can not exist without a UserSession but I am unclear on the rest. What about Product? It is defiently an entity but should it be associated to ShoppingCartItem?
Here are a few suggestion (they might all be incorrect implementations):
public interface IUserSession {
public Guid Id { get; set; }
public IList<IShoppingCartItem> ShoppingCartItems{ get; set; }
}
public interface IShoppingCartItem {
public Guid UserSessionId { get; set; }
public int ProductId { get; set; }
}
Another one would be:
public interface IUserSession {
public Guid Id { get; set; }
public IList<IShoppingCartItem> ShoppingCartItems{ get; set; }
}
public interface IShoppingCartItem {
public Guid UserSessionId { get; set; }
public IProduct Product { get; set; }
}
A third one is:
public interface IUserSession {
public Guid Id { get; set; }
public IList<IShoppingCartItemColletion> ShoppingCartItems{ get; set; }
}
public interface IShoppingCartItemColletion {
public IUserSession UserSession { get; set; }
public IProduct Product { get; set; }
}
public interface IProduct {
public int ProductId { get; set; }
}
I have a feeling my mind is too tightly coupled with database models and tables which is making this hard to grasp. Anyone care to decouple?
Looks like you are on the right track. Half of the whole "doing DDD right" is having the right base classes. Have a look at this great DDD applied to C# resource:
http://dddpds.codeplex.com/
The source code is available and is very readable.
So, with regards to having ID in the model. The ID is a database thing and the usual approach is to keep all persistence out of the Model and restrict the model to the business logic. However, one normally makes an exception for the identifier and buries it in the Model base class like so:
public class ModelBase {
protected readonly object m_Key;
public ModelBase(object key) {
m_Key = key;
}
}
This key is used by your persistence layer to talk to the database and is opaque. It's considered quite OK to downcast the key to the required type, because you know what it is.
Also, the Domain Objects are pretty much on the bottom of your architecture stack (just above the Infrastructure layer). This means that you can make them concrete classes. You will not have multiple implementations of the domain models, so the interfaces are unnecessary, which is what Domain Driven Design is about - Domain first.
public Class UserSession : ModelBase {
public UserSession(Guid Id):base(Id) {}
public Guid Id { get{ return m_Key as Guid;} }
public IList<ShoppingCartItem> ShoppingCartItems{ get; set; }
}
public class ShoppingCartItem : ModelBase {
public ShoppingCartItem ():base(null) {}
public UserSession UserSession { get; set; }
public Product Product { get; set; }
}
Typical shopping cart or customer-order examples prefer making UserSession (or Order) the root of aggregate. Individual items should be children of this session/order. It is up you whether individual items in the cart should have a meaningful id. I would prefer no, since 5 widgets in the cart are indistinguishable from another 5 widgets. Hence, I would model cart items as a collection of value objects.
Common problem with shopping cart items is whether they should include price, or not. if you include price, you will have your cart independent from changes of product price. It is very desirable if you want to store you cart for historical reasons since it is valuable to know how much items in the cart cost according to price when they were bought, not according to current.
Product should form definitively an aggregate by itself. Period.
Now, I don't know if all of this is easily implementable in LINQ to SQL, but you can try.