Relationships in Entity Framework Code First - c#

yesterday I created database in Management Studio and now I want to create it in program using EF Code First.
Here is link to my database: http://s11.postimg.org/6sv6cucgj/1462037_646961388683482_1557326399_n.jpg
And what I did:
public class GameModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreationTime { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string TotalTime { get; set; }
public DateTime RouteStartTime { get; set; }
public DateTime RouteEndTime { get; set; }
public int MaxPlayersPerTeam { get; set; }
public int CityId { get; set; }
public int CreatorId { get; set; }
[InverseProperty("Id")]
[ForeignKey("CreatorId")]
//public int TeamId { get; set; }
//[ForeignKey("TeamId")]
public virtual UserModel Creator { get; set; }
public virtual CityModel City { get; set; }
//public virtual TeamModel WinnerTeam { get; set; }
}
public class RegionModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<CityModel> Cities { get; set; }
}
public class CityModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int RegionId { get; set; }
public virtual RegionModel Region { get; set; }
public virtual ICollection<UserModel> Users { get; set; }
public virtual ICollection<GameModel> Games { get; set; }
}
public class UserModel
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public DateTime RegistrationDate { get; set; }
public string FacebookId { get; set; }
public int CityId { get; set; }
public virtual CityModel City { get; set; }
public virtual IEnumerable<GameModel> Games { get; set; }
}
For now I wanted to create 4 tables but I have some problems... I want to make CreatorId in GameModel, but it doesn't work... When i wrote UserId instead of CreatorId it was working ( without [InverseProperty("Id")] and [ForeignKey("CreatorId")]).
This is what i get:
The view 'The property 'Id' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type.' or its master was not found or no view engine supports the searched locations.
edit:
I changed it like this:
public int CityId { get; set; }
public int CreatorId { get; set; }
[ForeignKey("CityId")]
public virtual CityModel City { get; set; }
[ForeignKey("CreatorId")]
public virtual UserModel Creator { get; set; }
And there is another problem.
The view 'Introducing FOREIGN KEY constraint 'FK_dbo.UserModels_dbo.CityModels_CityId' on table 'UserModels' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.' or its master was not found or no view engine supports the searched locations.
And I have no idea how to solve it.

The InversePropertyAttribute specifies, which navigation property should be used for that relation.
A navigation property must be of an entity type (the types declared in your model, GameModel for example) or some type implementing ICollection<T>, where T has to be an entity type. UserModel.Id is an int, which clearly doesn't satisfy that condition.
So, the inverse property of GameModel.Creator could be UserModel.Games if you changed the type to ICollection<GameModel>, or had to be left unspecified. If you don't specify an inverse property, EF will try to work everything out on its own (in this case it would properly recognize GameModel.Creator as a navigation property, but UserModel.Games would most likely throw an exception, as it is neither an entity type, nor does it implement ICollection<T> with T being an entity type, nor is it a primitive type from a database point of view). However, EF's work-everything-out-by-itself-magic doesn't cope too well with multiple relations between the same entity types, which is when the InversePropertyAttribute is needed.
A quick example that demonstrates the problem:
class SomePrettyImportantStuff {
[Key]
public int ID { get; set; }
public int OtherId1 { get; set; }
public int OtherId2 { get; set; }
[ForeignKey("OtherId1")]
public virtual OtherImportantStuff Nav1 { get; set; }
[ForeignKey("OtherId2")]
public virtual OtherImportantStuff Nav2 { get; set; }
}
class OtherImportantStuff {
[Key]
public int ID { get; set; }
public virtual ICollection<SomePrettyImportantStuff> SoldStuff { get; set; }
public virtual ICollection<SomePrettyImportantStuff> BoughtStuff { get; set; }
}
Here, EF knows that it has to generate 2 FKs from SomePrettyImportantStuff to OtherImportantStuff with the names Id1 and Id2, but it has no way to tell which of the IDs refers to the entity where it was sold from and which is the one it was bought from.
Edit: How to fix the cyclic reference problem
To fix that problem, your context class should override OnModelCreating and configure the foreign keys which shouldn't cascade on delete accordingly, like this:
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Entity<CityModel>().HasMany(c => c.Users).WithRequired(u => u.City)
.HasForeignKey(u => u.CityId).WillCascadeOnDelete(value: false);
// Add other non-cascading FK declarations here
base.OnModelCreating(builder);
}

Related

The required column 'CustomerId' was not present in the results of a 'FromSql' operation

The error message is clear:
'The required column 'CustomerId' was not present in the results of a
'FromSql' operation'
But somehow I didn't really expect a CustomerId?
The error happens here:
contacts = db.Contacts.FromSql("SIP_API_MONDIA_Contacts_sel").ToList();
addresses = db.Addresses.FromSql("SIP_API_MONDIA_Address_sel").ToList();
Controller:
public IList<Customer> GetAllCustomers()
{
//Initialize the objects
IList<Customer> customers = null;
IList<Contacts> contacts = null;
IList<Addresses> addresses = null;
//Fetch the data from stored procedures
customers = db.Customers.FromSql("SomeProcName").ToList();
contacts = db.Contacts.FromSql("SomeProcName").ToList();
addresses = db.Addresses.FromSql("SomeProcName").ToList();
//Loop through customers and add the contact and addresses when required
foreach(var item in customers)
{
item.Contacts = contacts.Where(x => x.Customer == item.Id).ToList();
item.Addresses = addresses.Where(x => x.Customer == item.Id).ToList();
}
return customers;
}
The model:
public class Customer
{
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string VatCode { get; set; }
public string ChamberOfCommerceCode { get; set; }
public DateTime Modified { get; set; }
public DateTime Created { get; set; }
public string LanguageCode { get; set; }
public decimal Discount { get; set; }
public string CustomerManager { get; set; }
public Guid PriceList { get; set; }
public Guid PaymentCondition { get; set; }
// public bool VatLiable { get; set; }
public bool IsBlocked { get; set; }
public bool IsProspect { get; set; }
public bool IsSuspect { get; set; }
public string Website { get; set; }
public string DashboardUrl { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
// public ICollection<FreeFields> FreeFields { get; set; }
// public Dictionary<string, string> UknownElements { get; set; }
public ICollection<Contacts> Contacts { get; set; }
public ICollection<Addresses> Addresses { get; set; }
}
public class FreeFields
{
public string Key { get; set; }
public string Value { get; set; }
}
public class Contacts
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Initials { get; set; }
public string Function { get; set; }
public Guid Customer { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string LanguageCode { get; set; }
public bool IsMainContact { get; set; }
public string Gender { get; set; }
public string Username { get; set; }
}
public class Addresses
{
public Guid Id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string Postcode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string CountryCode { get; set; }
public string Type { get; set; }
public Guid Customer { get; set; }// This Property should be GUID instead of String..
public bool IsMainAddress { get; set; }
public string Route { get; set; }
public string State { get; set; }
}
I am not entirely sure what the error means with 'CustomerId'
The stored procedures return the 100% exact value of the models.
Edit in order to add print scrn of the sql resultset && DbContext:
public class IsahContext : DbContext
{
public IsahContext()
{
}
public IsahContext(DbContextOptions<IsahContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(Setting.ConnectionString);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
//Entities will come here
public DbSet<Customer> Customers { get; set; }
public DbSet<Addresses> Addresses { get; set; }
public DbSet<Contacts> Contacts { get; set; }
}
CustomerId is the conventional name for the Foreign Key of the one-to-many relationships introduced by the
public ICollection<Contacts> Contacts { get; set; }
public ICollection<Addresses> Addresses { get; set; }
collection navigation properties of the Customer class.
Although the related classes Contacts and Addresses contain a property Guid Customer, due to its name it's not recognized as a Foreign Key, so it falls into No Foreign Key Property category. And EF Core assumes a shadow property (and column) named CustomerId. Shadow property convention explanation is:
Shadow properties can be created by convention when a relationship is discovered but no foreign key property is found in the dependent entity class. In this case, a shadow foreign key property will be introduced. The shadow foreign key property will be named <navigation property name><principal key property name> (the navigation on the dependent entity, which points to the principal entity, is used for the naming). If the principal key property name includes the name of the navigation property, then the name will just be <principal key property name>. If there is no navigation property on the dependent entity, then the principal type name is used in its place.
In order to map the Customer property as a FK, you should use either ForeignKey attribute:
You can use the Data Annotations to configure which property should be used as the foreign key property for a given relationship. This is typically done when the foreign key property is not discovered by convention.
Tip
The [ForeignKey] annotation can be placed on either navigation property in the relationship. It does not need to go on the navigation property in the dependent entity class.
e.g. (since you have no navigation property in the dependent entities):
[ForeignKey(nameof(Contacts.Customer))]
public ICollection<Contacts> Contacts { get; set; }
[ForeignKey(nameof(Addresses.Customer))]
public ICollection<Addresses> Addresses { get; set; }
or Fluent API:
modelBuilder.Entity<Customer>()
.HasMany(customer => customer.Contacts)
.WithOne() // no nav property
.HasForeignKey(contact => contact.Customer); // the FK property
modelBuilder.Entity<Customer>()
.HasMany(customer => customer.Addresses)
.WithOne() // no nav property
.HasForeignKey(address => address.Customer); // the FK property
Could you please also post the relevant parts of the DB context class and an example result of the stored procedure.
Without those, I can only guess:
The Identity column is not marked with the [Key] attribute, nor it follows the standard naming convention of "EntityNameId" therefore it is not able to deduct the identity column.
So, I suggest adding the [Key] attribute to the Id property:
[Key]
public Guid Id { get; set; }
If that doesn't work, please post the context and the SP result.

Entity Framework C# Introducing A Foreign Key X In Table Y May Cause Cycles OR Multiple Cascade Paths

I am developing a C# MVC application. I am using Code First approach to model my database.
My project had the following requirements:
Company Can Have Many Products
Product Can have many Advertisement
Types
Here are model classes (code first solution) to the above mentioned problem.
public class Company
{
public Company()
{
this.Employees = new HashSet<ApplicationUser>();
}
public int ID { get; set; }
[Required]
public string Name { get; set; }
public string Logo { get; set; }
[Display(Name="Company Description")]
public string CompanyDescription { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public virtual ICollection<ApplicationUser> Employees { get; set; }
public virtual ICollection<Client> Clients { get; set; }
public ICollection<Product> Products { get; set; }
}
public class Product
{
public int ProductID { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public string ProductName { get; set; }
public int CompanyID { get; set; }
public virtual Company Company { get; set; }
public virtual ICollection<AdvertisementType> AdvertisementTypes { get; set; }
}
public class AdvertisementType
{
public int AdvertisementTypeID { get; set; }
public int ProductID { get; set; }
[Display(Name = "Advertisement Name")]
public string AdvertisementTypeName { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public virtual Product Product { get; set; }
}
When I try to update the database, after creating the migrations i get the following error:
Introducing FOREIGN KEY constraint 'FK_dbo.AdvertisementTypes_dbo.Products_ProductID' on table 'AdvertisementTypes' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
I have been trying solve this problem but unable to find any solution. I don't find any problem with the model classes, nor i think there are any issues with the relationship between the models.
Any suggestions or help will be useful.
EDIT
Here is screenshot of Tables and their relations
in your dbContext you need to turn cascade delete to false if you want to avoid that.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
You can initialize your make a List() in Product like you did with Company class...
public class Product
{
public int ProductID { get; set; }
public Product()
{
this.AdvertisementTypes = new List<AdvertisementType>();
}

Creating a controller for a model using EF (No key error)

I'm trying to create a controller with scaffolding based on the following model (with no previously created context, but I chose the option to create it alongside the controller):
namespace MvcMusicStorePractice.Models
{
public class Album
{
public virtual int AlbumId { get; set; }
public virtual int GenreId { get; set; }
public virtual int ArtistId { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
}
But I keep getting the following error:
Album::EntityType 'Album' has no key defined. Define the key for this EntityType.
I'v tried the following solutions:
Adding the [Key] attribute to the AlbumId;
Changing the public virtual int AlbumId to simply public int Id.
It still does not work however. Does anyone know what the problem is?
In order to use the entity framework, every entity needs a key. This is how EF tracks objects in its cache, posts updates back to the underlying data store, and links related objects together:
namespace MvcMusicStorePractice.Models
{
public class Album
{
[Key]
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
}
Mind the [key] annotation that will make that field the PK.
Also make sure to only use "Virtual" with foreign objects (Only Genre & Artist)/

Entity Framework multiple references to same table

I'm having trouble creating my database with EF code-first. I have an entity Player and an entity friedship.
Each friendship references two players. One of the players is the sender, the other one is the receiver of the friendship.
This are my entities:
Player.cs
public class Player
{
public int PlayerId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[InverseProperty("Receiver")]
public virtual List<Friendship> FriendshipsIncoming { get; set; }
[InverseProperty("Sender")]
public virtual List<Friendship> FriendshipsOutgoing { get; set; }
}
Friendship.cs
public class Friendship
{
public int FriendshipId { get; set; }
public int SenderId { get; set; }
public int ReceiverId { get; set; }
[ForeignKey("Sender")]
public Player Sender { get; set; }
[ForeignKey("Receiver")]
public Player Receiver { get; set; }
[Required]
public bool Confirmed { get; set; }
}
I tried implementing the relationsships the way shown in this tutorial:
http://www.entityframeworktutorial.net/code-first/inverseproperty-dataannotations-attribute-in-code-first.aspx
When trying to update the database with the "update-database" command i'm getting the following error message:
The ForeignKeyAttribute on property 'Receiver' on type 'Darta.WebApi.Models.Friendship' is not valid. The foreign key name 'Receiver' was not found on the dependent type 'Darta.WebApi.Models.Friendship'. The Name value should be a comma separated list of foreign key property names.
I also tried fixing the issue with fluent-api like shown here:
http://csharpwavenet.blogspot.sg/2013/06/multiple-foreign-keys-with-same-table.html
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Friendship>()
.HasRequired(b => b.Sender)
.WithMany(a => a.FriendshipsOutgoing)
.HasForeignKey(b=>b.SenderId);
modelBuilder.Entity<Friendship>()
.HasRequired(b => b.Receiver)
.WithMany(a => a.FriendshipsIncoming)
.HasForeignKey(b => b.ReceiverId);
}
In this case I'm getting the following error:
Introducing FOREIGN KEY constraint 'FK_dbo.Friendships_dbo.Players_SenderId' on table 'Friendships' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
You should only need either the DataAnnotations or the FluentAPI. You don't need both. If you want to use the [ForeignKey] and [InverseProperty] attributes, then get rid of the FluentAPI code.
Also, note that in the [ForeignKey] and [InverseProperty] attributes, you need to specify the name of the column, not the navigation property.
public class Player
{
public int PlayerId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[InverseProperty("ReceiverId")]
public virtual ICollection<Friendship> FriendshipsIncoming { get; set; }
[InverseProperty("SenderId")]
public virtual ICollection<Friendship> FriendshipsOutgoing { get; set; }
}
public class Friendship
{
public int FriendshipId { get; set; }
public int SenderId { get; set; }
public int ReceiverId { get; set; }
[ForeignKey("SenderId")]
public Player Sender { get; set; }
[ForeignKey("ReceiverId")]
public Player Receiver { get; set; }
[Required]
public bool Confirmed { get; set; }
}
I'll correct the answer. InverseProperty must be a valid entity type. So in this case Friendship.Receiver, Friendship.Sender
public class Player
{
public int PlayerId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[InverseProperty("Receiver")]
public virtual ICollection<Friendship> FriendshipsIncoming { get; set; }
[InverseProperty("Sender")]
public virtual ICollection<Friendship> FriendshipsOutgoing { get; set; }
}
public class Friendship
{
public int FriendshipId { get; set; }
public int SenderId { get; set; }
public int ReceiverId { get; set; }
[ForeignKey("SenderId")]
public Player Sender { get; set; }
[ForeignKey("ReceiverId")]
public Player Receiver { get; set; }
[Required]
public bool Confirmed { get; set; }
}

How do I establish a one-to-one relationship using Database First?

When my models were generated, many relationships were mapped automagically. However, some of the relationships are "incorrect" (or at least, not what I want), or missing.
I don't doubt that this is because of poor database design, but based on my role in this project there is not much I can do to fix that. However, is there something I can do in my application code to fix the mapping?
Here is one example:
I would like to map the StoreProductId property to the StoreProducts table.
ProductAttributePriceAdjustment
public partial class ProductAttributePriceAdjustment
{
public int AdjustmentId { get; set; }
public int StoreProductId { get; set; }
public int StoreId { get; set; }
public string ProductId { get; set; }
public Nullable<int> ProductSizeId { get; set; }
public Nullable<decimal> Adjustment { get; set; }
public int PointsAdjustment { get; set; }
public Nullable<int> ProductColorID { get; set; }
public StoreProduct StoreProduct { get; set; }
}
StoreProduct
public partial class StoreProduct
{
public int StoreProductID { get; set; }
public int StoreID { get; set; }
public string ProductID { get; set; }
public bool Featured { get; set; }
public bool Clearance { get; set; }
}
In my view, when I try calling something like:
#adjustment.StoreProduct.ProductID
I get this error:
Object reference not set to an instance of an object.
Update 1
I followed Frans' advice and updated my model to this:
public partial class ProductAttributePriceAdjustment
{
public int AdjustmentId { get; set; }
public int StoreProductId { get; set; }
public int StoreId { get; set; }
public string ProductId { get; set; }
public Nullable<int> ProductSizeId { get; set; }
public Nullable<decimal> Adjustment { get; set; }
public int PointsAdjustment { get; set; }
public Nullable<int> ProductColorID { get; set; }
public virtual StoreProduct StoreProduct { get; set; }
}
but am still getting the same error.
You cannot create a 1:1 mapping in entity framework like this. It's not supported.
Entity Framework only supports 1:1 mappings in which both tables have a shared primary key (ie they have the same primary key, and one of them is a foreign key to the other). In your situation, you are actually creating a 1 to many, because there is no guarantee that StoreProductId is unique.

Categories

Resources