Delete in cascade - asp.net

I'm new to asp.net and mvc.
I have a class AsyApp
public class AsyApp
{
[Key]
public int AsyAppId { get; set; }
[DisplayName("Nom")]
public string Name { get; set; }
public virtual ICollection<Scene> Scenes { get; set; }
}
It has a collection of scenes
public class Scene
{
[Key]
[Required]
public int SceneId { get; set; }
[ForeignKey("AsyApp")]
public int AsyAppId { get; set; }
[Required]
public virtual AsyApp AsyApp { get; set; }
[ForeignKey("Name")]
public int NameId { get; set; }
[DisplayName("Nom")]
public virtual Translation Name { get; set; }
public int Order { get; set; }
}
And the Scene has a property Name from a class Translation
public class Translation
{
[Key]
[Required]
public int TranslationId { get; set; }
public string Fr { get; set; }
public string En { get; set; }
}
Here is my issue.
I will use the class Translation to handle language for every single string in my application. I could be in any other classes
I would like that when I delete an application, it delete the appropriate scenes and localisations
Here is my code for deleting an app
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AsyApp asyApp = db.AsyApps.Find(id);
if (asyApp == null)
{
return HttpNotFound();
}
db.AsyApps.Remove(asyApp);
db.SaveChanges();
return RedirectToAction("Index");
}
The scenes seams to be deleted automaticaly but not the localisations associated with them...
Hope you can help me
Thanks a lot

look at this link:
https://msdn.microsoft.com/en-us/data/jj591620.aspx#CascadeDelete
you can enable cascade delete using Fluent API.

Related

How to call Db view file in repository pattern?

I am creating a view file in SQL Server as shown in the image below.
and I created a model to get results from this view:
public class FactALLCousumption : BaseEntity, IAggregateRoot
{
public double sumActiveImportTotal { get; set; }
public DateTime hour { get; set; }
public int fullDateAlternateKey { get; set; }
}
But I can't call this view in my repository. My repository code is bellow:
public class FactCousumptionRepository: GenericRepository<FactCousumption>, IFactCousumptionRepository
{
public DbContext _dbContext;
public FactCousumptionRepository(BaseDbContext context) : base(context)
{
_dbContext = context;
}
public async Task<FactALLCousumption> GetTotalAllCousumption()
{
}
}
In EF Core 2.2 or 2.1, you could use Query types.
According to the screenshot and the model to be used for the View you provided , I make a simple working demo like below , you could refer to and make the modification as per your demand:
1.Model
public class FactCousumption
{
public int Id { get; set; }
public double SumActiveImportTotal { get; set; }
public int DateKeyId { get; set; }
[ForeignKey("DateKeyId")]
public Dim_Date Dim_Date { get; set; }
public int TimeAltKeyId { get; set; }
[ForeignKey("TimeAltKeyId")]
public Dim_Time Dim_Time { get; set; }
public int TariffKeyId { get; set; }
[ForeignKey("TariffKeyId")]
public Dim_Tariff Dim_Tariff { get; set; }
}
public class Dim_Date
{
[Key]
public int DateKey { get; set; }
public int FullDateAlternateKey { get; set; }
public DateTime Date { get; set; }
public ICollection<FactCousumption> FactCousumptions { get; set; }
}
public class Dim_Time
{
[Key]
public int TimeAltKey { get; set; }
public DateTime Hour { get; set; }
public ICollection<FactCousumption> FactCousumptions { get; set; }
}
public class Dim_Tariff
{
[Key]
public int TariffType { get; set; }
public string TariffName { get; set; }
public ICollection<FactCousumption> FactCousumptions { get; set; }
}
2.Create SQL View
CREATE VIEW [dbo].[View1]
AS SELECT SUM(FactCousumption.SumActiveImportTotal) AS consumption ,Dim_Time.HOUR,Dim_Date.FullDateAlternateKey,Dim_Tariff.TariffName
FROM FactCousumption INNER JOIN
Dim_Date ON FactCousumption.DateKeyId = Dim_Date.DateKey INNER JOIN
Dim_Time ON FactCousumption.TimeAltKeyId=Dim_Time.TimeAltKey INNER JOIN
Dim_Tariff ON FactCousumption.TariffKeyId=Dim_Tariff.TariffType
GROUP BY Dim_Date.FullDateAlternateKey, Dim_Time.HOUR ,Dim_Tariff.TariffName
3.The model that is used for the view , note : the property name in model should be consistent with those in the view
public class FactALLCousumption
{
public double consumption { get; set; }
public DateTime hour { get; set; }
public int fullDateAlternateKey { get; set; }
}
4.DbContext , create a DbQuery property in my DbContext to consume the view results inside the Model and set up the View especially if you have different view name than your Class.
public DbQuery<FactALLCousumption> FactALLCousumption { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Query<FactALLCousumption>().ToView("View1");
}
5.Finally you can easily get the results of the View like this.
public async Task<FactALLCousumption> GetTotalAllCousumption()
{
var result = await _context.FactALLCousumption.FirstOrDefaultAsync();
return result;
}
Note: It's worth noting that DbQuery won't be/is not supported anymore in EF Core 3.0. See here

How to include multiple child objects?

I'm playing with new ASP.Net 5.0 WebApi and strugling to understand how to return more then one child object, or child of the child.
Lets say I have 4 classes:
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public int TypeId { get; set; }
public int ColourId { get; set; }
public virtual Type Type { get; set; }
public virtual Colour Colour { get; set; }
}
public class Type
{
public int Id { get; set; }
public string Name { get; set; }
public int TypeGroupId { get; set; }
public virtual TypeGroup TypeGroup { get; set; }
}
public class Colour
{
public int Id { get; set; }
public string Name { get; set; }
}
public class TypeGroup
{
public int Id { get; set; }
public string Name { get; set; }
}
And would like to return all the data for the car including Type, Colour, and even TypeGroup of the Type. How do I Do it?
When I do like this it includes only Type:
[HttpGet]
public IEnumerable<Car> Get()
{
return _dbContext.Cars.Include(c => c.Type);
}
This is my setup in Startup.cs:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
Is it possible to set to return every child object and grandchild and etc?
Many thanks
You can turn off lazy loading for all entities by using the following in your DbContext class (place this in the constructor):
this.Configuration.LazyLoadingEnabled = false;
This will disable it for all entities - so be wary of this and watch for performance issues.
Another way you can load all the entities for a particular class is to remove the virtual keyword from the property declarations.

How to make single view using viewmodel in asp.net mvc 4?

I have different models Image,Page & PageCategories
public class Image
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
}
public class Page
{
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public virtual PageCategory PageCategory { get; set; }
}
public class PageCategory
{
public int PageCategoryId { get; set; }
public string CategoryName { get; set;
public virtual ICollection<Page> Pages { get; set; }
}
DBContext Class is
class DemoContext:DbContext
{
public DbSet<PageCategory> PageCategories { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<Image> Images { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
I am wondering how to get all the model data to the home page using ViewModel.
For Ex.:
How to get image list and Page list in home page from multiple models?
You may want something like this :
viewModel :
//Create a viewModel with all the properties that you need
public class ViewModel
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public string CategoryName { get; set; }
}
Controller :
...
using (DemoContext db = new DemoContext()){
List<ImagePageViewModel> viewData = (from p in db.Page
join pc from db.PageCategory on p.PageCategoryId equals pc.PageCategoryId
select new ViewModel(){
PageTitle=p.PageTitle,
CategoryName = pc.CategoryName
//... set every property you want
})
}
return View(viewData );
note: I didn't add Image to the query because there is no explicit relation
between Image and the others table so i let you do it.
Create another class and define all above three into it. like below
public class MyView
{
public List<Image> Images { get; set; }
public List<Page> Pages { get; set; }
public List<PageCategory> PageCategories { get; set; }
}
Controller Action:-
public ActionResult Index()
{
MyView myView = // Get it using your logic
return View(myView);
}
finally got my answer:
public class ViewModelDemo
{
public IEnumerable<Image> images { get; set; }
public IEnumerable<Pages> pages { get; set; }
public IEnumerable<PageCategory> pagecategories { get; set; }
}
Then in HomeController
private DemoContext db=new DemoContext();
public ActionResult Index()
{
ViewModelDemo vm = new ViewModelDemo();
vm.images = db.Images.ToList();
vm.pages=db.Pagess.ToList();
vm.pagecategories=db.PageCategories.ToList();
return View(vm);
}

Save Relation between User and Entity in ASP.NET MVC4

I have an Exercise entity defined in my ASP.NET MVC4 Web Application.
I'm using the Form Authentication with the default AccountModels.cs class.
I have class which looks like
public class Exercise
{
private DateTime _DateCreated = DateTime.Now;
private UserProfile _Teacher;
public int Id{ get; set; }
public string Question { get; set; }
public int Anwser { get; set; }
public string Category { get; set; }
public int maxNbrOfAttempts { get; set; }
public string Hints { get; set; }
public virtual ICollection<Quiz> Quizzes { get; set; }
public DateTime Date
{
get { return _DateCreated; }
set { _DateCreated = value; }
}
public UserProfile Author
{
get { return _Teacher; }
set { _Teacher = value; }
}
}
Am I using the UserProfile correctly to link between an Exercise and a logged in user?
How can I get the current UserProfile in my controller?
Change it like this:
public class Exercise
{
public Exercise()
{
this.Date = DateTime.Now;
this.Author = User.Identity.Name; //Write this line if you want to set
//the currently logged in user as the Author
public int Id{ get; set; }
public string Question { get; set; }
public int Anwser { get; set; }
public string Category { get; set; }
public int maxNbrOfAttempts { get; set; }
public string Hints { get; set; }
public virtual ICollection<Quiz> Quizzes { get; set; }
public virtual DateTime Date { get; set; }
public virtual UserProfile Author { get; set; }
}

How to Update model and database with code first approach in Asp.net MVC

I'm new to mvc. I've creted an MVC app, in which i have used code first approach. Right now i have two tables Deal and Comment. Now i want to add a new table Category in the database and new column categoryId in Deal table.
How i can update database and model?
I'm using Sql Server 2008 R2 for Database.
I've following structure of class:
namespace FBWebApp.Models
{
public class Deal
{
public int ID { get; set; } // ID
public string Title { get; set; } // Titolo del deal
public string Description { get; set; } // Descrizione dell'annuncio
public string FacebookUID { get; set; } // UID facebook dell'utente
public string Visibility { get; set; } // Visibility
public string Category { get; set; }
public int Option1 { get; set; }
public int Option2 { get; set; }
public int Option3 { get; set; }
public int Option4 { get; set; }
public string PhotoURL { get; set; } // URL of the facebook photo profile
public string Name { get; set; } // Name of the user
public string ProfileUrl { get; set; } // URL of the facebook profile
public string Photo1 { get; set; } // URL of the Photo1 (local )
public string Photo2 { get; set; }
public string Photo3 { get; set; }
public string Photo4 { get; set; }
public string Photo5 { get; set; }
}
public class Comment
{
[Key]
public int CommentId { get; set; }
public string CommentText { get; set; }
public int ID { get; set; }
[ForeignKey("ID")]
public Deal DelNav { get; set; }
}
public class DealDBContext : DbContext
{
public DealDBContext() : base("DealDBContext") { }
public DbSet<Deal> Deals { get; set; }
public DbSet<Comment> Comments { get; set; }
}
}
Try using 'update-database -force -verbose' in the Package Manager Console.
If it doesn't work, modify the migration but typing 'add-migration somename' and it will apear in the Migrations folder.
If you are new to MVC and EF, definitely check out this tutorial. It explains all about that and everything else you need to know:
http://pluralsight.com/training/Player?author=scott-allen&name=mvc4-building-m1-intro&mode=live&clip=0&course=mvc4-building
first add your model :
public class Category
{
public int ID { get; set; }
public int cateName { get; set; }
}
in Deal class :
public class Deal
{
//..
[ForeignKey("CatId")]
public virtual Category Category { get; set; }
}
after Enable Migration you should use this command in console manager to update your database :
update-database

Resources