MVC - Seeding GUID and table key - c#

During seeding in MVC how can I prevent GUIDs being generated in the database?
This is my class:
[Table("Languages")]
public class Language
{
[Key]
public Guid ID { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 0)]
public string Name { get; set; }
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 0)]
public string Code { get; set; }
[DefaultValue(true)]
public bool IsEnabled { get; set; }
}
And this is my seed method:
protected override void Seed(SunLite.Models.SunLiteDBContext context)
{
public static SunLiteDBContext Run(SunLiteDBContext context)
{
context.Languages.AddOrUpdate
(
x => x.ID,
new Language { Name = "English", Code = "en-gb", ID = Guid.Parse("{fab5422a-f63d-4042-b7b1-705f69854bc9}"), IsEnabled = true },
new Language { Name = "Spanish", Code = "es", ID = Guid.Parse("{24380e18-02bf-4668-87ee-b2514d17f384} "), IsEnabled = true },
new Language { Name = "German", Code = "de", ID = Guid.Parse("{2c05c682-704f-43a4-864b-742ae359aa30}"), IsEnabled = true },
new Language { Name = "French", Code = "fr", ID = Guid.Parse("{bf929fe3-67a0-425c-81d2-1ef554affc7c} "), IsEnabled = true },
new Language { Name = "Turkish", Code = "tr", ID = Guid.Parse("{9d09cb45-3d0d-4238-a903-96c4f17481a1} "), IsEnabled = true }
);
}
}
At the moment this data is added to the database each time with new guids, not the ones I specified.

You can add attribute [DatabaseGenerated(DatabaseGeneratedOption.None)] to your ID property. It should help.

Related

TryValidateProperty fails with error "'The type 'Customer' does not contain a public property named 'Address.City'. (Parameter 'propertyName')'"

Trying to use TryValidateProperty to validate Customer class, it fails validate on Address property which is another class. I'm getting this error
System.ArgumentException: 'The type 'Customer' does not contain a public property named 'Address.City'. (Parameter 'propertyName')'
public class Customer
{
[Required(ErrorMessage = "{0} is mandatory")]
[MaxLength(50, ErrorMessage = "The {0} can not have more than {1} characters")]
public string Name { get; set; }
[Required(ErrorMessage = "{0} is mandatory")]
[Range(0, 150, ErrorMessage = "The Age should be between 0 and 150 years")]
public int Age { get; set; }
[Required(ErrorMessage = "{0} is mandatory")]
public Address? Addresse { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
Validator.TryValidateProperty(this.Name,
new ValidationContext(this, null, null) { MemberName = "Name" },
results);
Validator.TryValidateProperty(this.Age,
new ValidationContext(this, null, null) { MemberName = "Age" },
results);
Validator.TryValidateProperty(this.Addresse.City, new ValidationContext(this, null, null) { MemberName = "Address.City" }, results);
return results;
}
}
var customer = new Customer()
{
//Name = "hello",
EntryDate = DateTime.Today,
Password = "AAAA",
PasswordConfirmation = "BBBB",
Age = -1,
Addresse = new Address()
{
//City = "CTG",
Street = "Goli"
}
};
var validationContext = new ValidationContext(customer);
var resultAdd = customer.Validate(validationContext);
How to validate the Address properties?
TIA.
I got it working making the following changes in Validate method. Need to pass the context correctly to the Validator.
public class Customer
{
[Required(ErrorMessage = "{0} is mandatory")]
[MaxLength(50, ErrorMessage = "The {0} can not have more than {1} characters")]
public string Name { get; set; }
[Required(ErrorMessage = "{0} is mandatory")]
[Range(0, 150, ErrorMessage = "The Age should be between 0 and 150 years")]
public int Age { get; set; }
[Required(ErrorMessage = "{0} is mandatory")]
public Address? Addresse { get; set; }
public IEnumerable<ValidationResult> Validate()
{
var results = new List<ValidationResult>();
Validator.TryValidateProperty(this.Name,
new ValidationContext(this, null, null) { MemberName = "Name" },
results);
Validator.TryValidateProperty(this.Age,
new ValidationContext(this, null, null) { MemberName = "Age" },
results);
Validator.TryValidateProperty(this.Addresse.City, new ValidationContext(this.Address, null, null) { MemberName = "City" }, results);
return results;
}
}
var customer = new Customer()
{
//Name = "hello",
EntryDate = DateTime.Today,
Password = "AAAA",
PasswordConfirmation = "BBBB",
Age = -1,
Addresse = new Address()
{
//City = "CTG",
Street = "Goli"
}
};
var result = customer.Validate();
Hope it helps someone.

NotMapped prop Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

good day ..
i created a model that has an property with [Notmapped] DataAnnotations and i created another class inherit from this model with same property but i add required DataAnnotations the problem is when i delete i got error "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
"
My Model :
[Key]
[Display(AutoGenerateField = true, AutoGenerateFilter = true, Description = "IDDescription", GroupName = "IDGroupName", Name = "IDName", ShortName = "IDShortName", Prompt = "IDPrompt", Order = 50, ResourceType = typeof(Resources.BaseEntity))]
public long ID { get; set; }
[StringLength(207, ErrorMessageResourceName = "StringTooMuch", ErrorMessageResourceType = typeof(Resources.BaseSlider))]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "DetailsRequired", ErrorMessageResourceType = typeof(Resources.BaseSlider))]
[Display(Name = "Description", ResourceType = typeof(Resources.BaseSlider))]
public string Description { get; set; }
[NotMapped]
public string ShortDescription
{
get
{
if (Description.Length <= 207)
{
return Description;
}
return Description.Substring(0, 207);
}
}
[Display(Name = "HasBTN", ResourceType = typeof(Resources.BaseSlider))]
public bool HasBTN { get; set; }
[Display(Name = "Is Image Dark")]
public bool IsDark { get; set; }
[Display(Name = "Link", ResourceType = typeof(Resources.BaseSlider))]
public string Link { get; set; }
[Display(Name ="Slider Type")]
public long SliderTypeID { get; set; }
[NotMapped]
//[ImageValidation(".jpg,.png,.japg", OriginalWidth = 1920, OriginalHeight = 600)]
[Display(AutoGenerateField = true, AutoGenerateFilter = true, Description = "ImagePathDescription", Name = "ImagePathName", ResourceType = typeof(Resources.BaseMore))]
public virtual HttpPostedFileBase ImagePathFile { get; set; }
#endregion
#region Relations
public virtual IList<BaseSliderPhotoUpload> Photos { get; set; }
public virtual BaseLookup SliderType { get; set; }
#endregion
public BaseSlider()
{
Photos = new List<BaseSliderPhotoUpload>();
}
and the class i created :
public class BaseSliderCreate : BaseSlider
{
#region Data
[NotMapped]
[Required]
//[ImageValidation(".jpg,.png,.japg", OriginalWidth = 1920, OriginalHeight = 600)]
[Display(AutoGenerateField = true, AutoGenerateFilter = true, Description = "ImagePathDescription", Name = "ImagePathName", ResourceType = typeof(Resources.BaseMore))]
public override HttpPostedFileBase ImagePathFile { get; set; }
#endregion
}
in delete actionresult code :
public ActionResult DeleteConfirmed(Guid id)
{
BaseSlider SliderObject = db.Sliders.Where(x => x.GUID == id && x.Deleted == null).FirstOrDefault();
SliderObject.Deleted = DateTime.Now;
SliderObject.DeletedByID = _CurrentUser.ID;
// Delete All Photos
DeletePhoto DeletePhoto = new DeletePhoto();
var DeletedPhotoName = new List<string>();
foreach (var name in SliderObject.Photos)
{
DeletedPhotoName.Add(name.FileName);
}
if (DeletePhoto.PhotoDeleted("Slider", DeletedPhotoName))
{
try
{
db.SliderPhotos.RemoveRange(SliderObject.Photos);
db.Entry(SliderObject).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
ErrorList.Add(ex.Message);
throw;
}
}
else
{
ErrorList.Add(DeletePhoto.ErrorMessage);
}
ViewBag.ErrorList = ErrorList;
return RedirectToAction("Delete", new { id = SliderObject.GUID });
}
when i save change i got error
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
i checked i found the EntityValidationErrors is that ImagePathFile is required..
thanks for helping my and i apologist for my bad English

Entity Framework Seed method not running

I'm having some trouble getting the Seed method of EF to run. I've run update-database in the PMC - but no effect on the DB. Here's the method:
public class PhilosopherInitialiser : System.Data.Entity.DropCreateDatabaseIfModelChanges<PhilosopherContext>
{
protected override void Seed(PhilosopherContext context)
{
var philosophers = new List<Philosopher>{
new Philosopher {
FirstName = "Bertrand",
LastName = "Russell",
DateOfBirth = DateTime.Parse("1872-05-18"),
DateOfDeath = DateTime.Parse("1970-02-02"),
IsAlive = false,
NationalityID = 1,
AreaID = 7,
Description = "Here's some text about Bertrand Russell"
},
new Philosopher {
FirstName = "Immanuel",
LastName = "Kant",
DateOfBirth = DateTime.Parse("1724-04-22"),
DateOfDeath = DateTime.Parse("1804-02-12"),
IsAlive = false,
NationalityID = 3,
AreaID = 1,
Description = "Here's some text about Immanuel Kant"
},
new Philosopher {
FirstName = "John",
LastName = "Rawls",
DateOfBirth = DateTime.Parse("1921-02-21"),
DateOfDeath = DateTime.Parse("2002-11-24"),
IsAlive = false,
NationalityID = 9,
AreaID = 3,
Description = "Here's some text about John Rawls"
}
};
philosophers.ForEach(p => context.Philosophers.Add(p));
context.SaveChanges();
var nationalities = new List<Nationality>
{
new Nationality { Name = "English" },
new Nationality { Name = "Scotish" },
new Nationality { Name = "German" },
new Nationality { Name = "French" },
new Nationality { Name = "Greek" },
new Nationality { Name = "Italian" },
new Nationality { Name = "Spanish" },
new Nationality { Name = "Russian" },
new Nationality { Name = "American" }
};
nationalities.ForEach(n => context.Nationalities.Add(n));
context.SaveChanges();
var areas = new List<Area>{
new Area { Name = "Metaphysics" },
new Area { Name = "Existentialism" },
new Area { Name = "Political philosophy" },
new Area { Name = "Philosophy of the mind" },
new Area { Name = "Aesthetics" },
new Area { Name = "Social philosophy" },
new Area { Name = "Logic" },
new Area { Name = "Moral philosophy" },
new Area { Name = "Epistemology" }
};
areas.ForEach(a => context.Areas.Add(a));
context.SaveChanges();
var books = new List<Book>
{
new Book {
Title = "The impact of science on society",
PhilosopherID = 1,
AreaID = 6
},
new Book {
Title = "The analysis of mind",
PhilosopherID = 1,
AreaID = 4
},
new Book {
Title = "Marriage and morals",
PhilosopherID = 1,
AreaID = 8
},
new Book{
Title = "Critique of pure reason",
PhilosopherID = 2,
AreaID = 9
},
new Book{
Title = "The metaphysics of morals",
PhilosopherID = 2,
AreaID = 8
},
new Book{
Title = "A theory of justice",
PhilosopherID = 3,
AreaID = 3
}
};
books.ForEach(b => context.Books.Add(b));
context.SaveChanges();
}
}
}
And here's my PhilosopherContext class:
public class PhilosopherContext : DbContext
{
public PhilosopherContext() : base("PhilosopherContext")
{
}
public DbSet<Philosopher> Philosophers { get; set; }
public DbSet<Area> Areas { get; set; }
public DbSet<Nationality> Nationalities { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Book>()
.HasRequired(p => p.Philosopher)
.WithMany()
.HasForeignKey(p => p.PhilosopherID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Philosopher>()
.Property(p => p.DateOfBirth)
.HasColumnType("datetime2");
modelBuilder.Entity<Philosopher>()
.Property(p => p.DateOfDeath)
.HasColumnType("datetime2");
}
}
}
Inside the Web.Config file I'm using initialising the DB here:
<contexts>
<context type="PhilosophersLibrary.DAL.PhilosopherContext, PhilosophersLibrary">
<databaseInitializer type="PhilosophersLibrary.DAL.PhilosopherInitialiser, PhilosophersLibrary" />
</context>
</contexts>
Does anyone have any suggestions? I feel that the method might not be called.
UPDATE
I seem to be making progress. The Areas and Nationalities tables are being seeded with the data. But I have to comment out the Philosophers data and the Books data. Is there something wrong with my data model?
public class Book
{
public int BookID { get; set; }
public string Title { get; set; }
[Display(Name = "Philosopher")]
public int PhilosopherID { get; set; }
[Display(Name = "Area")]
public int AreaID { get; set; }
public virtual Philosopher Philosopher { get; set; }
public virtual Area Area { get; set; }
}
public class Philosopher
{
// <className>ID pattern causes property to be primary key
public int PhilosopherID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Display(Name = "Date of birth")]
public DateTime DateOfBirth { get; set; }
[Display(Name = "Date of death")]
public DateTime DateOfDeath { get; set; }
public Boolean IsAlive { get; set; }
public string Description { get; set; }
// Foreign keys have corresponding navigation properties
// <NavigationProperty>ID naming convention cause EF to identify foreign keys
public int NationalityID { get; set; }
public int AreaID { get; set; }
// Navigation properties - defined as virtual to use LazyLoading
// Nationality and Area have a 1 to 1 relationship with philosopher
// Books has a 1 to many relationship with philosopher
public virtual Nationality Nationality { get; set; }
public virtual Area Area { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
Try to use this:
CreateDatabaseIfNotExists<PhilosopherContext>
instead of this:
DropCreateDatabaseIfModelChanges<PhilosopherContext>
Also I would add:
public PhilosopherContext() : base("PhilosopherContext")
{
Database.SetInitializer<PhilosopherContext>(new CreateDatabaseIfNotExists<PhilosopherContext>());
}

Using Validator.TryValidateObject in ASP.NET MVC

Validator.TryValidateObject everytime return true. Why? I tried different field values.
Its my model:
public class CompanyPreviewMeta
{
[Required]
[Display(Name="Изображение")]
public string Image { get; set; }
[Required]
[Display(Name="Текст")]
[StringLength(100, MinimumLength = 20, ErrorMessage = "Значение {0} должно содержать от {2} до 100 символов.")]
public string Text { get; set; }
}
It's my validation, and "valid" is true everytime:
ValidationContext ValidatorContext = new ValidationContext(model, null, null);
List<ValidationResult> result = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(model, ValidatorContext, result, true);

How to create entity with nested via LINQ to SQL

I got one entity linked with another:
[Table(Name = "Employees")]
public sealed class Employee
{
[Column(Name = "Id", UpdateCheck = UpdateCheck.Never, IsPrimaryKey = true, IsDbGenerated = true, DbType = "Int NOT NULL IDENTITY")]
public int Id { get; set; }
[Column(Name = "Phone", UpdateCheck = UpdateCheck.Never, DbType = "Char(20)")]
public string Phone { get; set; }
[Column(Name = "UserId", UpdateCheck = UpdateCheck.Never, DbType = "Int NOT NULL")]
public int UserId { get; set; }
[Association(Storage = "_user", ThisKey = "UserId")]
public User User
{
get { return _user.Entity; }
set { _user.Entity = value; }
}
private EntityRef<User> _user;
}
[Table(Name = "Users")]
public sealed class User
{
[Column(Name = "Id", UpdateCheck = UpdateCheck.Never, IsPrimaryKey = true, IsDbGenerated = true, DbType = "Int NOT NULL IDENTITY")]
public int Id { get; set; }
[Column(Name = "LastName", UpdateCheck = UpdateCheck.Never, DbType = "NVarChar(100)")]
public string LastName { get; set; }
[Column(Name = "FirstName", UpdateCheck = UpdateCheck.Never, DbType = "NVarChar(100)")]
public string FirstName { get; set; }
}
Then I want to create an employee:
var entity = new Employee
{
Phone = "Some",
User = new User
{
FirstName = "Some",
LastName = "Some"
}
};
context.GetTable<Employee>().InsertOnSubmit(entity);
context.SubmitChanges();
And got this:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Employees_Users"
Is it posible to create linked entities in LINQ to SQL?
Try specifying the OtherKey property of the AssociationAttribute as well. If not specified, it will default to the key of the related class, but in your case the names of the keys in the different classes are different (UserId vs Id).
[Association(Storage = "_user", ThisKey = "UserId", OtherKey="Id")]
public User User
{
get { return _user.Entity; }
set { _user.Entity = value; }
}
private EntityRef<User> _user;

Categories

Resources