Entity Framework invalid cast saving new tph record - entity-framework-core

Source code for this problem is on GitHub
I have the following dbContext for a legacy data structure.
[TypesInfoInitializer(typeof(OrgsContextInitializer))]
public class OrgsEFCoreDbContext : DbContext
{
public OrgsEFCoreDbContext(DbContextOptions<OrgsEFCoreDbContext> options) : base(options)
{
}
public DbSet<ModuleInfo> ModulesInfo { get; set; }
public DbSet<ModelDifference> ModelDifferences { get; set; }
public DbSet<ModelDifferenceAspect> ModelDifferenceAspects { get; set; }
public DbSet<PermissionPolicyRole> Roles { get; set; }
public DbSet<ApplicationUser> Users { get; set; }
public DbSet<ApplicationUserLoginInfo> UserLoginInfos { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<CustomerContact> CustomerContacts { get; set; }
public DbSet<SupplierContact> SupplierContacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUserLoginInfo>(b =>
{
b.HasIndex(nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.LoginProviderName), nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.ProviderUserKey)).IsUnique();
});
modelBuilder.Entity<Organization>().ToTable("Organizations");
modelBuilder.Entity<Organization>().HasDiscriminator(x => x.OrganizationType)
.HasValue<Customer>(1)
.HasValue<Supplier>(2)
;
modelBuilder.Entity<Contact>().ToTable("Contacts");
modelBuilder.Entity<Contact>().HasDiscriminator(x => x.ContactType)
.HasValue<CustomerContact>(1)
.HasValue<SupplierContact>(2)
;
}
}
When I add a CustomerContact to a Customer I get an error
Unable to cast object of type 'Orgs.Module.BusinessObjects.CustomerContact' to type 'Orgs.Module.BusinessObjects.SupplierContact'.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.get_Item(IPropertyBase propertyBase)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.GetCurrentValue(IPropertyBase propertyBase)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.TryAddPropertyNameToCollection(InternalEntityEntry entity, ICollection`1 propertiesToCheck, IPropertyBase property)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.TryAddPropertyNameToCollection(InternalEntityEntry entity, IProperty property, ICollection`1 propertiesToCheck)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.GetPropertiesToCheck(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckReadWritePermissionsForNonIntermediateObject(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckReadWritePermissions(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.CheckIsGrantedToSave(InternalEntityEntry entity)
at DevExpress.EntityFrameworkCore.Security.NetStandard.ChangeTracking.SecurityStateManager.GetEntriesToSave(Boolean cascadeChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at DevExpress.ExpressApp.EFCore.EFCoreObjectSpace.DoCommit()
at DevExpress.EntityFrameworkCore.Security.SecuredEFCoreObjectSpace.DoCommit()
at DevExpress.ExpressApp.BaseObjectSpace.CommitChanges()
at DevExpress.ExpressApp.Win.SystemModule.WinModificationsController.Save(SimpleActionExecuteEventArgs args)
at DevExpress.ExpressApp.SystemModule.ModificationsController.saveAction_OnExecute(Object sender, SimpleActionExecuteEventArgs e)
at DevExpress.ExpressApp.Actions.SimpleAction.RaiseExecute(ActionBaseEventArgs eventArgs)
at DevExpress.ExpressApp.Actions.ActionBase.ExecuteCore(Delegate handler, ActionBaseEventArgs eventArgs)
The error is the other way around if I try to add a supplier contact to a supplier.
The business classes are as follows;
[NavigationItem("Data")]
public class Customer : Organization
{
public Customer()
{
Contacts = new List<CustomerContact>();
}
public virtual List<CustomerContact> Contacts { get; set; }
}
public class CustomerContact : Contact
{
public CustomerContact() {}
[ForeignKey("OrganizationId")]
public virtual Customer Customer { get; set; }
}
public abstract class Organization
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Comments { get; set; }
public int OrganizationType { get; set; }
}
public abstract class Contact
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int ContactType { get; set; }
public int OrganizationId { get; set; }
}
At run time the user experience is
Looking at the instructions here I am unsure if this is a Dev Express issue or an Entity Framework issue.

Related

EF Core 7 - error occurred: the entity type 'List<string>' requires a primary key to be defined

I get an error when I use EF Core 7 to create entities.
The entity type 'List' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.
I have found the error prop, that's Project of service entity, when I only annotate Project of service entity, then I can run Add-Migration successfully. I don't know why and I also don't know how to fix this error.
Does somebody know this error? Please help...
public class Service : EntityBase
{
public Guid? DefaultCapacityUnitId { get; set; }
public Guid? DefaultSizeUnitId { get; set; }
public virtual SizeUnit DefaultSizeUnit { get; set; }
public Guid ProjectId { get; set; }
public Project Project { get; set; }
public Guid? ParentId { get; set; }
public virtual Service Parent { get; set; }
public Guid DisciplineId { get; set; }
public virtual Discipline Discipline { get; set; }
public virtual List<Service> SubServices { get; set; } = new List<Service>();
}
public class Equipment : EntityBase
{
public Guid ProjectId { get; set; }
public Project Project { get; set; }
public Guid? ServiceId { get; set; }
public virtual Service Service { get; set; }
public Guid DisciplineId { get; set; }
public virtual Discipline Discipline { get; set; }
}
public abstract class EntityBase
{
[Key]
public virtual Guid Id { get; set; } = Guid.NewGuid();
private string name;
[Required, MaxLength(200)]
public virtual string Name
{
get
{
return name?.Trim();
}
set
{
name = value?.Trim();
}
}
private string shortName;
[Required, MaxLength(100)]
public virtual string ShortName
{
get
{
return shortName?.Trim();
}
set
{
shortName = value?.Trim();
}
}
[NotMapped]
public EntityBase Snapshot { get; set; }
[NotMapped]
public List<string> ValueChangedProperties { get; set; } = new List<string>();
}
public class Project : EntityBase
{
}
public class Discipline : EntityBase
{
public Guid ProjectId { get; set; }
public virtual Project Project { get; set; }
public virtual List<Service> Services { get; set; } = new List<Service>();
public Guid? ScenarioId { get; set; }
public Guid? ParentId { get; set; }
public virtual Discipline Parent { get; set; }
}
public partial class TestDbContext : DbContext
{
public TestDbContext(DbContextOptions<TestDbContext> options)
: base(options)
{ }
public TestDbContext()
{
}
public DbSet<Project> Projects { get; set; }
public DbSet<Discipline> Disciplines { get; set; }
public DbSet<Service> Services { get; set; }
public DbSet<ServiceGroup> ServiceGroups { get; set; }
public DbSet<SizeUnit> SizeUnits { get; set; }
public DbSet<Equipment> Equipments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var entityTypes = typeof(TestDbContext).GetProperties()
.Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
.Select(p => p.PropertyType.GetGenericArguments()[0]).ToList();
entityTypes.ForEach(entityType => {
var entityName = entityType.Name;
modelBuilder.Entity(entityType).ToTable(entityName);
});
modelBuilder.Entity<ServiceMapping>().HasOne(x => x.Service).WithMany().HasForeignKey(x => x.ServiceId).OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<ServiceMapping>().HasOne(x => x.TargetService).WithMany().HasForeignKey(x => x.TargetServiceId).OnDelete(DeleteBehavior.Cascade);
base.OnModelCreating(modelBuilder);
}
}
public class ServiceGroup : EntityBase
{
public Guid ProjectId { get; set; }
public virtual Project Project { get; set; }
public Guid? ScenarioId { get; set; }
}
public class ServiceMapping : EntityBase
{
public Guid ProjectId { get; set; }
public virtual Project Project { get; set; }
public Guid ServiceId { get; set; }
public virtual Service Service { get; set; }
public Guid TargetServiceId { get; set; }
public virtual Service TargetService { get; set; }
}
public class SizeUnit : EntityBase
{
public Guid ProjectId { get; set; }
public virtual Project Project { get; set; }
public int UnitType { get; set; }
}
If I annotate Project of service entity, then it's all right.

EFCore Generic Repository and UnitOfWork Design Pattern

when im trying to create new data and save it, im getting error at the
public int Complete()
{
return _context.SaveChanges();
}
and error is saying me that:
The value of 'Agency.ID' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known. .
i have a Base class like that:
public class Base
{
protected Base()
{
CreatedDate = DateTime.Now;
IsDeleted = false;
ModifiedDate = null;
}
public int ID { get; set; }
public int? CreatedUserId { get; set; }
public int? ModifiedUserId { get; set; }
public string CreatedUserType { get; set; }
public string ModifiedUserType { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public bool? IsActive { get; set; }
public bool? IsDeleted { get; set; }
}
i have a Agency class like that :
public class Agency : Base
{
public Agency()
{
AgencyIsComplated = false;
}
[Required, StringLength(255)]
public string AgencyName { get; set; }
[Required, StringLength(255)]
public string AgencyPhoto { get; set; }
[Required, StringLength(255)]
public string AgencyEMail { get; set; }
[Required, StringLength(13)]
public string AgencyPhone { get; set; }
[StringLength(13)]
public string AgencyBPhone { get; set; }
[StringLength(255)]
public string AgencyInfo { get; set; }
[Required, StringLength(255)]
public string AgencyTitle { get; set; }
[Required, StringLength(255)]
public string AgencyLink { get; set; }
public int AgencyExportArea { get; set; } // Join table ile yapılacak,ayrı bir tabloda tutulacak
[Required, StringLength(255)]
public string AgencyInstagram { get; set; }
public string AgencyTwitter { get; set; }
public string AgencyFacebook { get; set; }
public string AgencyLinkedin { get; set; }
public string AgencyYoutube { get; set; }
public bool AgencyIsComplated { get; set; }
[ForeignKey("CompanyID")]
public Company Company { get; set; }
[ForeignKey("LogID")]
public Log Log { get; set; }
public virtual ICollection<AgencyCompany> AgencyCompanies { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Log> Logs { get; set; }
}
public class AgencyConfiguration : IEntityTypeConfiguration<Agency>
{
public void Configure(EntityTypeBuilder<Agency> builder)
{
builder.HasKey(agency => agency.ID);
builder.HasMany(a => a.Logs)
.WithOne(a => a.Agency)
.HasForeignKey(a=>a.ID)
.OnDelete(DeleteBehavior.Restrict);
builder.HasMany(us => us.Users)
.WithOne(us => us.Agency)
.HasForeignKey(au=>au.ID)
.OnDelete(DeleteBehavior.Restrict);
builder.HasMany(ac => ac.AgencyCompanies)
.WithOne(ac => ac.Agency)
.OnDelete(DeleteBehavior.Restrict);
}
}
and i have got a UnitOfWork like that:
public class UnitOfWork : IUnitOfWork
{
private TradeTurkDBContext _context;
public UnitOfWork(TradeTurkDBContext context)
{
_context = context;
RepositoryAgency = new RepositoryAgency(_context);
}
public IRepository Repository { get; private set; }
public IRepositoryAgency RepositoryAgency { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
im inheriting that ID on my Base Model.
the problem is getting solved when im not defining ID in the base model but i allready set up my mapping on it.
so how can i solve that error without using AgencyID in the Agency model ?
The foreign key is in the details (or child) table. Therefore, e.g. a user, should have an AgencyId as foreign key.
builder.Entity<User>()
.HasOne(u => u.Agency)
.WithMany(a => a.Users)
.HasForeignKey(u => u.AgencyId)
.OnDelete(DeleteBehavior.Restrict);
This key automatically points to the primary key of the master (or parent) table.
User.ID is a primary key. User.AgencyId is a foreign key which (automatically) relates to the primary key Agency.ID.
E.g. see: Configure One-to-Many Relationships using Fluent API in Entity Framework Core

How to fix "Exception: Invalid channel" error in my API

I'm trying to save a object Using HTTP Post Method in my API Controller, but it's returning a error, i've tried to do the same in another controler and it works. I hope you may help!
The Request that I tried:
{
"integrationServiceHost": "10.80.80.10",
"RouterHost": "10.80.80.10",
"Enabled": "false",
"IntegrationServiceRemotePort": "1234",
"RouterSocketPort":"1234",
"RouterRemotePort":"1234",
"IDChannelBehavior":"10",
"IDEPS":"1",
"Description":"Teste Whats",
"IDChannel":"0"
}
ChannelWhatsapp Class:
public class ChannelWhatsApp : Channel
{
public ChannelWhatsApp();
[Column("WHATSAPP_UserName")]
public string UserName { get; set; }
[Column("WHATSAPP_Password")]
public string Password { get; set; }
[Column("WHATSAPP_DisplayName")]
public string DisplayName { get; set; }
}
url : http://172.19.22.81:5000/api/channelWhatsapp/saveDto
Channel Class :
public abstract class Channel : NotifyPropertyChanged
{
public Channel();
public virtual ICollection<Interaction> Interaction { get; set; }
public virtual ICollection<Schedule> Schedule { get; set; }
public virtual ICollection<Queue> Queue { get; set; }
public virtual ICollection<Session> Session { get; set; }
public virtual ChannelBehavior ChannelBehavior { get; set; }
public virtual EPS EPS { get; set; }
public DateTime? DtLastChange { get; set; }
[MaxLength(100)]
public string IntegrationServiceHost { get; set; }
[MaxLength(100)]
public string RouterHost { get; set; }
public bool Enabled { get; set; }
public int? IntegrationServiceRemotePort { get; set; }
public int? RouterSocketPort { get; set; }
public int? RouterRemotePort { get; set; }
[ForeignKey("ChannelBehavior")]
public int IDChannelBehavior { get; set; }
[ForeignKey("EPS")]
public int IDEPS { get; set; }
[MaxLength(200)]
public string Description { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int IDChannel { get; set; }
[NotMapped]
public string IconName { get; set; }
[NotMapped]
public byte? PendingPauseCode { get; set; }
[NotMapped]
public bool IsPausePending { get; set; }
[NotMapped]
public SystemUserOperator Operator { get; set; }
[NotMapped]
public DateTime StateMomment { get; set; }
[NotMapped]
public UserStateType CurrentState { get; set; }
public virtual ICollection<ChannelSkill> ChannelSkills { get; set; }
[NotMapped]
public ChannelTypeType Type { get; set; }
}
My Controller:
[Route("api/ChannelWhatsapp/{Action}")]
[ApiController]
public class ChannelWhatsappController : IrideController<ChannelWhatsApp>
{
public ChannelWhatsappController(IrideContext context) : base(context) { }
[HttpPost("")]
[ActionName("saveDto")]
public IActionResult saveDto([FromBody] ChannelWhatsApp entity)
{
try
{
////Obtem o data
//entity.DtLastChange = IrideUtil.getDate() ;
//_context.Set<ChannelWhatsApp>().Update(entity);
//_context.SaveChanges();
return Ok(entity);
}
catch (Exception ex)
{
return Ok(ex.ToString());
}
}
}
returned error:
Exception: Invalid channel IrideCM.Model.Channel..ctor()
IrideCM.Model.ChannelWhatsApp..ctor() lambda_method(Closure )
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject(JsonReader
reader, JsonObjectContract objectContract, JsonProperty
containerMember, JsonProperty containerProperty, string id, out bool
createdFromNonDefaultCreator) in JsonSerializerInternalReader.cs
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader
reader, Type objectType, JsonContract contract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty containerMember,
object existingValue) in JsonSerializerInternalReader.cs
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader
reader, Type objectType, bool checkAdditionalContent) in
JsonSerializerInternalReader.cs
When posting a payload to a controller in the request's body, you need to make sure the payload's structure matchs the structure of the expected class.
In your case, it does not match at all. You just need to post a payload with the same type as the type expected in the FromBody param of your endpoint.

EF6: How to make Custom Entity from Multiple Tables

Using the Northwind database, I have generated all of the entities from that table using EF6.
Now I would like to create an additional custom entity, which is not an existing table, but it pulls data from three existing tables. The custom entity is "OrderCustomized".
public class OrderCustomized
{
public int OrderID { get; set; }
public DateTime? OrderDate { get; set; }
public string CustomerID { get; set; }
public string CustomerContactName { get; set; }
public string CustomerPhone { get; set; }
public int? EmployeeID { get; set; }
public string EmployeeLastName { get; set; }
public string EmployeeFirstName { get; set; }
}
public partial class NorthwindEntities : DbContext
{
public NorthwindEntities()
: base("name=NorthwindEntities")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//throw new UnintentionalCodeFirstException();
modelBuilder.Entity<OrderCustomized>()
.Map(m =>
{
m.Properties(o => new { o.OrderID, o.OrderDate, o.CustomerID, o.EmployeeID });
m.ToTable("Order");
})
.Map(m =>
{
m.Properties(c => new { c.CustomerID, c.CustomerContactName, c.CustomerPhone });
m.ToTable("Customer");
})
.Map(m =>
{
m.Properties(e => new { e.EmployeeID, e.EmployeeLastName, e.EmployeeFirstName });
m.ToTable("Employee");
})
;
base.OnModelCreating(modelBuilder);
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Contact> Contacts { get; set; }
public virtual DbSet<CustomerDemographic> CustomerDemographics { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Order_Detail> Order_Details { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<Region> Regions { get; set; }
public virtual DbSet<Shipper> Shippers { get; set; }
public virtual DbSet<Supplier> Suppliers { get; set; }
public virtual DbSet<Territory> Territories { get; set; }
public virtual DbSet<OrderCustomized> OrdersCustomized { get; set; }
}
I keep getting the error "The entity type OrderCustomized is not part of the model for the current context."
How do I made OrderCustomized part of the model for the current context?
I would really appreciate any sample code, as I cannot find any when searching the internet.
Thanks,
Kellie
Remember to update T4 file (.tt extension). Let me know does it work after that operation.

One to many relation with cascade giving error

I am learning EF Code First with migrations, I have 3 entities :
[User] 1--->* [Call] 1--->* [ETA]
Code :
User.cs
public class User
{
[Key]
public int Id { get; set; }
public Guid LongId { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Call> Calls { get; set; } // many calls
public User()
{
LongId = Guid.NewGuid();
}
}
Call.cs
public class Call
{
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string BreakdownNo { get; private set; }
[Required,MaxLength(32)]
public string Customer { get; set; }
[Required,MaxLength(32)]
public string TrailerNo { get; set; }
[Required, MaxLength(32)]
public string DepotContact { get; set; }
[Required, MaxLength(48), RegularExpression(#"^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$")]
public string DepotEmail { get; set; }
[Required, MinLength(9), MaxLength(32)]
public string DepotPhone { get; set; }
[Required, MaxLength(32)]
public string DriverContact { get; set; }
[Required, MinLength(9), MaxLength(32), RegularExpression(#"^(7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$")]
public string DriverPhone { get; set; }
[Required, MaxLength(256)]
public string LocatedAtFreeText { get; set; }
[Required, MaxLength(8), RegularExpression(#"^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {0,1}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$")]
public string LocatedAtPostCode { get; set; }
[Required, MaxLength(16)]
public string StartupNo { get; set; }
[Required]
public bool IsLoaded { get; set; }
[Required, MaxLength(256)]
public string FaultDescription { get; set; }
[Required]
public DateTime StartTime { get; set; }
public DateTime? EndTime { get; set; }
public string Status { get; set; }
public virtual User Controller { get; set; } // 1 controller
public virtual ICollection<ETA> ETAs { get; set; } // many ETAs
public Call()
{
StartTime = DateTime.Now;
ETAs = new List<ETA> { new ETA() };
Status = "Logged";
}
}
ETA.c
public class ETA
{
[Key]
public int Id { get; set; }
[Required]
public TimeSpan Value { get; set; }
public int CallId { get; set; }
public ETA()
{
Value = TimeSpan.FromMinutes(90);
}
}
I would like it so when I delete the User it deletes all of the Calls for the User, which in turn deletes all of the ETAs for those Calls.
When I delete a User row from the Database (using database explorer) it gives me an error :
No rows were deleted.
A problem occurred attempting to delete row 201.
Error Source: .Net SqlClient Data Provider.
Error Message: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Calls_dbo.Users_Controller_Id". The conflict occurred in database "BreakdownDb", table "dbo.Calls", column 'Controller_Id'.
You can turn on the Cascade Delete option in Entity Framework, here you will find more info:
http://blogs.msdn.com/b/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx
The solution was to add OnModelCreating method to my DbContext class :
public class BreakdownDb : DbContext
{
public DbSet<Call> Calls { get; set; }
public DbSet<User> Users { get; set; }
public BreakdownDb(): base("name=DefaultConnection") {}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(x => x.Calls).WithRequired();
modelBuilder.Entity<Call>().HasMany(x => x.ETAs).WithRequired();
}
}