ABP - How delete depended items from entity - entity framework - asp.net-mvc

i have this entity Page:
public class Page : FullAuditedEntity<int, User>, IMultiLanguageEntity<PageTranslation>
{
public string Name { get; set; }
public string Content{ get; set; }
public Page()
{
Translations = new List<PageTranslation>();
}
public virtual IList<PageTranslation> Translations { get; set; }
}
And entity PageTranslation:
[Table("PageTranslations")]
public class PageTranslation : Entity<int>, IEntityTranslation<Page>
{
public Page Core { get; set; }
public int CoreId { get; set; }
public string Language { get; set; }
public string Name { get; set; }
public string Content{ get; set; }
}
I want to update page entity with updated values and tranlsations, so I call this service:
public void UpdatePage(UpdatePageInput input)
{
var item = _pageRepository.Get(input.Id);
item.Content = input.Content;
item.Description = input.Description;
item.Title = input.Title;
item.Name = input.Name;
item.Translations.Clear(); // there is a problem
item.Translations.addRange(input.Translations);
}
When I call item.Translations.Clear() method I got this exception:
The operation failed: The relationship could not be changed because
one or more of the foreign-key properties is non-nullable. When a
change is made to a relationship, the related foreign-key property is
set to a null value. If the foreign-key does not support null values,
a new relationship must be defined, the foreign-key property must be
assigned another non-null value, or the unrelated object must be
deleted.
How to solve this in ABP - http://www.aspnetboilerplate.com/?
Thanks for help !

While assuming u have a DBContext:
U can declare the on delete action:
protected override void OnModelCreating(DbModelBuilder modelBuilder){
modelBuilder.Entity<Page>()
.HasOptional(a => a.Translations)
.WithMany()
.WillCascadeOnDelete(true);
}

did you try
_pageRepository.DeleteAll();

Related

EntityType 'SelectListItem' has no key defined. Define the key for this EntityType

i Have a Model Class
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public ICollection<SelectListItem> CourseList { get; set; }
}
and the
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
and i try ti use it as
List<Student> sList = db.Students.ToList();
and i am getting following error
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'SelectListItem' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'SelectListItems' is based on type 'SelectListItem' that has no keys defined.
Please suggest where i am doing wrong.
Add [NotMapped] annotation to the LIST class
[NotMapped]
public List<SelectListItem> ListItems { get; set; }
NotMapped Code first convention dictates that every property that is of a supported data type is represented in the database. But this isn’t always the case in your applications. For example you might have a property in the Blog class that creates a code based on the Title and BloggerName fields. That property can be created dynamically and does not need to be stored. You can mark any properties that do not map to the database with the NotMapped annotation such as this BlogCode property.
[NotMapped]
public string BlogCode
{
get
{
return Title.Substring(0, 1) + ":" + BloggerName.Substring(0, 1);
}
}
You can refer to the link here on EF code first Data Annotations
You should not be attempting to store SelectListItem in the database, as this is MVC specific concept. Instead create a custom entity class and use it instead;
public class Course
{
public int CourseId { get; set; }
public string CourseTitle { get; set; }
}
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public ICollection<Course> CourseList { get; set; }
}
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
}

Getting error The 'proprrty1' property on 'table1' could not be set to a 'System.Int64' value. in my mvc application

I am getting an error in my mvc application. I am trying to display record from my sql table using entity framework. here is the code which i am trying. But I dnt know why this code giving me error
This is my model
[Table("tbInsertMobile")]
public class tbInsertMobile
{
[Key]
public int MobileID { get; set; }
public string MobileName { get; set; }
public string MobileIMEno { get; set; }
public string mobileprice { get; set; }
public string mobileManufacured { get; set; }
}
my another class in model
public class EmployeeContext:DbContext
{
public DbSet<tbInsertMobile> usermobiles { get; set; }
}
This the code of my contoller
public ActionResult Index(int id)
{
EmployeeContext employeeContext = new EmployeeContext();
tbInsertMobile employee = employeeContext.usermobiles.Single(x => x.MobileID == id);
return View(employee);
}
and now the error which i am getting is this
The 'MobileID' property on 'tbInsertMobile' could not be set to a 'System.Int64' value. You must set this property to a non-null value of type 'System.Int32
Experts Tell me where I am getting this error
Thanks
The answer is there already in the comment.
It's trying to assign a long to an int. Change MobileID to be long. – CodeCaster

Initilialize Navigation Property when creating new Entity with Breeze

I have simple Model defined as
public class Project
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int StatusId { get; set; }
public virtual Status Status { get; set; }
}
public class Status
{
public int Id { get; set; }
public string Name { get; set; }
}
So, currently If I try to create a new Project Entity with breeze, it initializes the navigation property "Status" with null. How can I initialize it with default value? Note that, I don't want any binding with drop down field for this field at least for create operation.
function createNewProject() {
return manager.createEntity('Project');
}
You can define a custom constructor for the Project entity type and set a default StatusId value in there. The Status navigation property will be set to the relevant status entity (assuming the entity is in the breeze cache). For example:
function Project() {
this.StatusId = desiredDefaultStatusEntityId;
}
var manager = new breeze.EntityManager('...');
manager.metadataStore.registerEntityTypeCtor('Project', Project);
Take a look at Extending entities for some more information on extending entities.

Lazy loading does not work in entity framework 5

I have defined a (poco?) class in my domain project:
public class Club
{
public Club()
{
ContactPersons = new HashSet<ContactPerson>();
}
public int Id { get; set; }
[Required]
[StringLength(64)]
public string Name { get; set; }
public virtual ICollection<ContactPerson> ContactPersons { get; set; }
}
public class ContactPerson
{
public virtual int Id { get; set; }
[StringLength(64)]
public virtual string FirstName { get; set; }
[StringLength(64)]
public virtual string LastName { get; set; }
}
In my MVC project I have my clubcontroller:
public ActionResult Create(CreateClubViewModel model)
{
Club club = new Club();
model.Initialize(club);
IClubDb clubDb = DependencyResolverHelper.IClubDbService;
clubDb.Create(club); // create club in db
}
public ActionResult Display(string domain)
{
try
{
IClubDb clubDb = DependencyResolverHelper.IClubDbService;
Club club = clubDb.Get(domain);
return View(club);
}
catch (Exception) // user is not logged iin
{
return View();
}
}
Finally, in my DB project I create and retrieve the club,
public Club Get(string name)
{
return DataContext.Clubs
//.Include(x => x.ContactPersons)
.Single(r => r.Name == name);
}
public int Create(Club club)
{
DataContext.Clubs.Add(club);
return DataContext.SaveChanges();
}
I have tried everything to get EF to lazy load the ContactPersons of my club object when I call the Get club in the Display method but ContactPersons has always a length of zero. However, if I eager load contact persons using the .include (I have commented this part out), then obviously ContactPersons contains a number of contacts.
I am not sure what I am doing wrong:
I have followed the guidelines for defining poco classes: http://msdn.microsoft.com/en-us/library/dd468057.aspx
I have a public parameter less constructor (but not protected constructor)
I have lazyloading enabled
I think I am missing a concept, the poco club class is also my domain entity which I insert into DB. What am I doing wrong? Whay I can't get lazy loading to work?
try
ContactPersons.ToList();
this will force all entities to be loaded.
see Entity framework, when call ToList() it will load FK objects automatically?
It seems that your LazyLoading performs when your dbContext is closed. So it will not load.
You use ContactPerson in view, am i right?
Did you forget to include the foreign key in your entity?
public class ContactPerson
{
public virtual int Id { get; set; }
[StringLength(64)]
public virtual string FirstName { get; set; }
[StringLength(64)]
public virtual string LastName { get; set; }
public int ClubId { get; set; }
[ForeignKey("ClubId")]
public virtual Club Club { get; set; } // if you need
}

How to set an attribute in a model that doesn't belong to the database

Inside of my model I have an attribute called attributes that its value is taken from the cutomized_attributes in my Database the property attributes does Not exist in the Database its just calculated value, while I'm trying to do the following I'm facing this error:
Error: System.Data.Entity.Edm.EdmEntityType: : EntityType 'JToken' has no key defined. Define the key for this EntityType
Model:
public class Restaurant
{
public int id{ get; set; }
public string name{ get; set; }
public string cutomized_attributes { get; set; }
private JObject _attributes { get; set; }
public JObject attributes
{
get
{
if (this._attributes == null)
return this._attributes = RestaurantAttributes.parseAttrString(this.cutomized_attributes);
return this._attributes;
}
set
{
this._attributes = value;
}
}
}
assuming you are using code first... within the dbcontext subclass
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Restaurant>().Ignore(x => x.attributes);
}

Resources