asp.net mvc enable on delete cascade for entire project - asp.net-mvc

I've searched for something that solves my problem, but don't seem to find anything.
Is there a way to simply enable OnDeleteCascade for the entire project?
Can anyone help please?

You want to setup your relationships in your DbContext and specify your cascade deletes in your model builder.
public class SomeContext : DbContext
{
public DbSet<EntityOne> EntityOnes { get; set; }
public DbSet<EntityTwo> EntityTwos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityOne>()
.HasRequired(d => d.EntityTwo)
.WillCascadeOnDelete(true); // this is what you want to do
}
}
Reference: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application
Reference (This one is really good for various relationships): https://msdn.microsoft.com/en-us/library/jj591620(v=vs.113).aspx
EDIT: Wanted to note this is called Entity Framework Fluent API if you wanted to google for some more info.

Related

Entity Framework Database First Classes and Table Names

I am trying to add .edmx to my web api application. The table names in our database are long and cumbersome like tbl_Company, tbl_User_Logins, tbl_Company_Departments. I would like to use neat class names like Company, User, Departments that map to these tables. I have been trying to find sample code to do this, but I feel like I am not "asking the right questions" which is why I can't find any answer.
I tried creating classes for "Department" and "User", and I tried adding code like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>().ToTable("tbl_Company_Departments_xlu");
modelBuilder.Entity<User>().ToTable("tbl_User_Logins");
}
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Department> Departments { get; set; }
but it didn't work when I tried to add a new department using Departments.Add(department). I am obviously missing a step, but I do not know what it is. I am new to this and am struggling. Any assistance is greatly appreciated.

Why need use OnModelCreating (MVC 5 EF code first)?

I don't understand what is the reason of using OnModelCreating function?
when I can do something like
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int Id { get; set; }
public Int LanguageId { get; set; }
[ForeignKey("LanguageId")]
public Language Language { get; set; }
Maybe I am wrong but when I reads about this,it is explained as it's for Many-to-Many relationship.
so why not do something like this.
ICollection<User> Users
For making relationship between entities, we have two options
DataAnnotation (Which you are using)
Fluent API.
When we are using fluent API we need to specify our relationship in this OnModelCreating(DbModelbuilder modelbuilder) method.So when model is created first time they should maintain relationship between entities.
Common Example for using this method is given in this below code snnipet
modelBuilder.Entity<Department>().Property(t => t.Name).HasMaxLength(50);
the same can be achieved using data annotation attribute.
[MaxLength(50)]
public string Name {get;set;}
So if you dont want to use DataAnotation Use Fluent API to serve your purpose.

What is the best way to use migrations with MVC5 and .Net Identity?

I'm just putting myself through the paces learning MVC5 with EF6 and Code First and have run into some confusion...
How are people managing their DbSets with the Identity changes, especially with Migrations?
Are you managing two sets of Migrations or putting your normal DbSets into the IdentityModel.cs file?
This is what I have currently:
public class ApplicationUser : IdentityUser
{
}
public class AoecContext : IdentityDbContext
{
public AoecContext()
: base("DefaultConnection")
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Faculty> People { get; set; }
public DbSet<SitePage> SitePages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<SitePage>().HasOptional(p => p.CourseDetails);
}
}
Is that a good idea, or just plain bad?
Your concerns are a bit better separated if you keep your IdentityDbContext separate from your DomainDbContext, but then you would need to manage two sets of migrations (among other things). As you have it you'll only need one set of migrations. I wouldn't consider what you're doing "bad" necessarily- it really depends on the project.
If its any consolation, the project that we are currently working on uses only one DbContext that also inherits from IdentityDbContext as yours does. It does pull in some references to the Data Access project that I wish weren't there, but it does greatly simplify working with EF in terms of database generation, persistence, and migrations. Whether we'll outgrow it in the future or not is hard to say.

How dependant is breezjs serverside contexprovider to entityframework?

I am building a WebApi for a CMS that has its own data provider. No DBContext or entity framework involved.
I have previously used breeze as it being such a breeze to map the server side model to the client:)
I have wondering if I can extend my code or breeze in a way such I get all the stuff from brezejs for free.
What I have to work with is the following Interfaces that I have made implementations for based on the data provider from the CMS.
public interface IC1Repository<T>
{
IQueryable<T> GetAll();
T Add(T item);
void Remove(T item);
bool Update(T item);
}
Its generic, so thats not going to work on the client.
I can generate a context class i guess that holds all the types exposed.
public class mycontext
{
public IC1Repository<Category> Categories { get; set; }
public IC1Repository<Customer> Customers { get; set; }
public IC1Repository<Employee> Employees { get; set; }
}
What would my next steps be to get this workign with breeze. Are there any interfaces i can implement such it mimics the DbContext. Can i maybe crate my custom DbSet that do not talk with a database, but just is a implementation of my IC1Repository above?
Any advices thanks :)
I think you want the ContextProvider which is the base class of the EFContextProvider.
That has the same semantics and same base behavior as the EFContextProvider but it doesn't use EF.
Check out the "No DB" sample which uses the ContextProvider to manage queries and saves to an in-memory "database".
Ignore the fact that this class sits in a DLL with references to EF. I realize that is annoying. But your project will compile and run just fine when there are no EF assemblies around. You can delete all the EF stuff if you used NuGet to get the Breeze.WebApi.dll.

Accessing stored procedures on a code generated DbContext with Entity Framework 4.1 with DDD

I'm working on a large project using ASP.Net MVC 3, EF 4.1 and Ninject for Dependecy Injection. I've read through many of the existing questions here regarding DDD, EF and the Repository Pattern but I can't seem to find anyone incorporating stored procedures with these patterns.
I don't like the idea of implementing yet another repository pattern on top of what seems to already be a UnitOfWork/RepositoryPattern already defined with a DbContext. Also, I generally don't like the idea of creating Service and Repository classes for every type of entity in the system if possible.
The source of my problem stems from this common repository interface which everyone seems to use.
public interface IRepository<TEntity> where TEntity : class
{
TEntity Get(Expression<Func<TEntity, bool>> whereClause);
IEnumerable<TEntity> List();
IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> whereClause);
void Add(TEntity entity);
void Delete(TEntity entity);
// And so on...
}
That's great if all your queries can be in context of a single entity. Where this breaks for me is when I want to access a stored procedure. With EF 4.1 & Code Generatrion you can add stored procedures (e.g. SelectUser) and it will generate a context which looks something like this.
namespace MyCompany.Data.Database
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using MyCompany.Domain.Entities;
using MyCompany.Domain.Contracts;
public partial class MyCompanyEntities : DbContext
{
public MyCompanyEntities()
: base("name=MyCompanyEntities")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Order> Orders { get; set; }
public DbSet<User> Users { get; set; }
public virtual ObjectResult<User> SelectUser(Nullable<int> userId)
{
((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(typeof(User).Assembly);
var userIdParameter = userId.HasValue ?
new ObjectParameter("UserId", userId) :
new ObjectParameter("UserId", typeof(int)); MyCompanyEntities x; x.
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<User>("SelectUser", userIdParameter);
}
public virtual ObjectResult<User> SelectUser(Nullable<int> userId, MergeOption mergeOption)
{
((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(typeof(User).Assembly);
var userIdParameter = userId.HasValue ?
new ObjectParameter("UserId", userId) :
new ObjectParameter("UserId", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<User>("SelectUser", mergeOption, userIdParameter);
}
}
}
As part of my DDD setup I have a UserService class and I would like to 'inject' a repository to its constructor. Many examples suggest that the constructor should accept an (IRepository<User> userRepository). This doesn't work for me. Stored procedures are generated on the DbContext class as a method and I am unable to see it.
The only thing I can think of is to either create another interface with the stored procedure methods on it. I don't really want to add it to the generic IRepository because then when you have an instance of IRepository<Order> you'll still see SelectUser which seems a bit odd. Maybe it's not a big deal?
Perhaps I'm going about this the wrong way. Should I not be bothering with creating an interface on top of my DbContext if I'm not trying to create a whole new repository pattern? I was really creating it for the dependency injection. Would it be wrong if the UserService constructor took a MyCompanyEntities instance instead of an interface?
What you found is natural. The problem is that generic repository is insufficient for real scenarios. It is only good for "base" implementation. You need specific repository for User entity which will expose method wrapping call to context exposed stored procedure.

Resources