How to update PostgreSQL database while using .NET 5? - c#

I start to learn .NET 5 to create full-stack applications. I create a model with the following code:
public class Contact
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[DataType(DataType.PostalCode)]
public int Zip { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Emanil { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
// Seting up Date & Time
public DateTime Created { get; set; }
// Seting up using of image
[NotMapped]
[Display(Name = "Image")]
[DataType(DataType.Upload)]
public IFormFile ImageFile { get; set; }
public byte[] ImageData { get; set; }
public string ImageType { get; set; }
// Thinking about primary key that the database will manage
public int Id { get; set; }
// Let's think about a derive property (a combination of firstname & lastname)
[NotMapped]
public string FullName { get { return $"{FirstName} {LastName}"; } }
}
Unfortunately, after creating the app I saw a typo mistake in Email => Emanil.
Now after correcting the typo I try: Add-Migration EmailUpdate but it fails, I do try Update-Database as well still fail, I make corrections on each line were I have Emanil to Email:
public async Task<IActionResult> Create([Bind("FirstName,LastName,Address1,Address2,City,State,Zip,Emanil,Phone,Created,ImageData,ImageType,ImageFile,Id")] Contact contact)
Just want to know the best way to update it (I use Visual Studio for the project).

Related

Why entity framework is referencing a column that doesn't even exist?

My project is throwing error
Invalid column name 'InitialsID_InitialsID'.
public User ValidateUser(string Username, string Password)
{
return uow.UserRepository.GetQueryable().Where(x => x.UserName == Username && x.Password == Password).FirstOrDefault();
}
Even there's no column by that name in the whole solution.
I had generated a migration script and it had that name in it but I changed that to InitialsID but still it asks for the same name.
How do I resolve it? I tried putting ForeignKey attribute etc but nothing works.
User.cs
public class User
{
public int UserID { get; set; }
public int UserGroupID { get; set; }
public UserGroup UserGroup { get; set; }
public string UserName { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Designation { get; set; }
public string Password { get; set; }
public bool? PasswordExpire { get; set; }
public DateTime? ExpiryDate { get; set; }
public bool Status { get; set; }
public DateTime? CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
public string Office { get; set; }
public string Station { get; set; }
public Initials InitialsID { get; set; }
}
Initials.cs
public class Initials
{
public short InitialsID { get; set; }
public string Code { get; set; }
}
I am using Code First approach.
Problem is in your foreign key configuration. When you are referencing navigation property public Initials InitialsID { get; set; }, EF is adding an implicit foreign key for this navigation property and it is by convention navigationPropery_navigationPropertyPrimaryKey and hence it is InitialsID_InitialsID
If you really want public Initials Initials { get; set; } navigaation property in User model class then write your foreign key configuration as follows:
public class User
{
public int UserID { get; set; }
public int UserGroupID { get; set; }
......................
public short InitialsId { get; set; }
public Initials Initials { get; set; }
}
It seems your database not migrated with new model or new models property,
Pleas migrate your database.
If you are using dotnet core, in cmd on the project folder type:
dotnet ef migrations add [name]
and then:
dotnet ef databae update

Code-First Entity Framework Custom Id Generated

Is it possible to create generated Id with code-first EF, so basically I want to create Id string with custom format
here is my code, something like this.
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
[DefaultValue("some script maybe")]
public string IdCustomer
{
get
{
return value from attribute script DefaultValue
}
private set {};
}
[DataType(DataType.PhoneNumber)]
[RegularExpression(#"(\()?(\+62|62|0)(\d{2,3})?\)?[ .-]?\d{2,4}[ .-]?\d{2,4}[ .-]?\d{2,4}", ErrorMessage = "Not a valid Phone number")]
public string Custno { get; set; }
[Required(ErrorMessage = "Input is required.")]
public string FirstName { get; set; }
public string LastName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public string CompanyName { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string UpdatedBy { get; set; }
public DateTime UpdatedDate { get; set; }
}
is it possible doing something like that, or any other idea to solved that issue

EF Update DB Enable Migration Navigational Property Error

I am using EF Migrations with MVC 5 - however I'm getting what I think/thought was/is a pretty common error, but the common solutions I've seen, I've already got:
The property 'companyId' cannot be configured as a navigation property.The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type.
From looking around my code looks correct, and worked prior to enable-migrations and update-database to see whether the test data in my system gets wiped before I put this change live. Within the ASN model I've added a string property of testAsn to see whether this gets added as a column to the database.
I am unsure if this error is relating to the ASN or the Contacts table/model, but they both have the same implementation.
Have I misunderstood regarding the use of navigational properties? Any help would be greatly appreciated.
Models
[Table("Company")]
public class Company
{
[Key]
public int companyId { get; set; }
[Required(ErrorMessage="Company name required.")]
[StringLength(100)]
public string name { get; set; }
[Required(ErrorMessage = "Telephone required.")]
public string telephone { get; set; }
[Required(ErrorMessage="Registration Number required.")]
[StringLength(30)]
public string regNumber { get; set; }
// navigation properties of the models that belong to the company
public virtual IList<Asn> asns { get; set; }
public virtual IList<Contact> contacts { get; set; }
}
[Table("Asn")]
public class Asn
{
[Key]
public int asnId { get; set; }
public int companyId { get; set; }
[ForeignKey("companyId")]
// property I'm adding to test whether migrations is working
public string testAsn { get; set; }
// *******************************
// as pointed out in the correct answer, the property below
// this comment should be above testAsn
// *******************************
public virtual Company company { get; set; }
[Required] // always has value
public bool userBehalf { get; set; }
[Required] // always has value
public bool confirmAssignment { get; set; }
[Required(ErrorMessage="Prefix required.")]
public string prefixAnnounced { get; set; }
[Required(ErrorMessage="Pending Ticket ID required.")]
public string pendingTicket { get; set; }
[DataType(DataType.MultilineText)]
public string comments { get; set; }
public bool asNumType { get; set; }
public string reason { get; set; }
}
[Table("Contact")]
public class Contact
{
[Key]
public int contactId { get; set; }
public int companyId { get; set; }
[ForeignKey("companyId")]
public virtual Company company { get; set; }
[StringLength(100, MinimumLength=3)]
[Required(ErrorMessage="Contact name required.")]
public string name { get; set; }
[Required(ErrorMessage="Telephone required.")]
[StringLength(30, MinimumLength=11)]
public string telephone { get; set; }
[Required]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}" +
#"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
#".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
ErrorMessage = "Email is not valid.")]
public string email { get; set; }
[Required(ErrorMessage = "Contact type required.")]
public string type { get; set; }
}
You have misplaced the ForeignKey attribute in the Asn class. Instead of putting it on the company property, it's on the testAsn property.

Passing a model with two classes to view in asp.net with EF5

I am new to ASP.NET and EF5. I am doing a project in VS2012, MVC4 using EF5.
I have a class CreateClient where there is further two classes Clients, FullPackages like below:
public class CreateClient
{
public Clients Clients { get; set; }
public List<FullPackages> FullPackages { get; set; }
}
Class Clients is like this:
[Table("tblClients")]
public class Clients
{
public int Id { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Maximum {1} characters allowed for {0} field")]
public string Username { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Minimum {2} characters required for {0} field", MinimumLength = 5)]
public string Password { get; set; }
[Required]
public string Name { get; set; }
public string Email { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string Contact { get; set; }
[Required]
public string Mobile { get; set; }
public string Description { get; set; }
}
and Class FullPackages is:
public class FullPackages
{
public int Id { get; set; }
public int TypeId { get; set; }
[Display(Name = "Package Type")]
public string TypeName { get; set; }
public int AllowedSMS { get; set; }
[Display(Name = "Time Span in Days")]
public int? TimeSpan { get; set; }
public decimal Price { get; set; }
[Display(Name = "Package Name")]
public string Name { get; set; }
}
I invoked this model in my view like
#model SmsServer.Models.CreateClient
and used the Clients class as
#Html.LabelFor(model => model.Clients.Username)
but i don't know to use the List<FullPackages> i want to use the values of list. I researched the site but didn't find any useful ideas.So Please help me.... on how to use it
OR is there any way to do this in a more simpler way :)
If you simply want to list them out you could do this:
<table>
<tr>
<th>Id</th>
<th>TypeName</th>
</tr>
#foreach(var package in Model.FullPackages)
{
<tr>
<td>#package.Id</td>
<td>#package.TypeName</td>
</tr>
}
</table>
Please note that if you want to post them back you will have to use an indexed loop instead of the foreach.

EF Puts wrong relationship in datatabse

I got this project were a Operator can have many roles.
Let me start out with the code so you can see what i mean.
TDOperator:
[DisplayName("Operator")]
public class TDOperator
{
public int TDOperatorId { get; set; }
[DisplayName("First Name")]
[Required]
public string FirstName { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email Adress")]
public string EmailAddress { get; set; }
[Required]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[HiddenInput(DisplayValue = true)]
public DateTime LastLogin { get; set; }
public List<string> RoleNames
{
get
{
return Roles.Select(x => x.Name).ToList();
}
}
public virtual ICollection<Role> Roles { get; set; }
[Required]
[DisplayName("Topdesk Username")]
public string TDUserName { get; set; }
public virtual ICollection<TDOperator> Coaches { get; set; }
public List<string> CoachNames
{
get
{
return Coaches.Select(x => x.ToString()).ToList();
}
}
public virtual ICollection<TDOperator> Pupils { get; set; }
public List<string> PupilNames
{
get
{
return Pupils.Select(x => x.ToString()).ToList();
}
}
public override string ToString()
{
return this.FirstName + " " + this.LastName;
}
}
And the one for Role
public class Role
{
public int RoleID { get; set; }
public string Name { get; set; }
public int Priority { get; set; }
}
Sorry for messy code I intent to clean that up later.
When i run this it Generated a database with 3 Tables with columns:
- TDOperatorTDOperators
1.TDOperator_TDOperatorId
2.TDOperator_TDOperatorId1
- TDOperators
1.TDOperatorId
2.FirstName
3.LastName
4.EmailAdress
5.UserName
6.PassWord
7.LastLogin
8.TDUsername
- Roles
1.RoleId
2.Name
3.Priority
4.TDOperator_TDOperatorId <<--- WTF!
The problem with this is that i can now only assign a role To 1 user. There can only be 1 admin and 1 user for example. It is supposed to create and extra Foreign Key table but it doesnt!
Please help out.
You are not telling Entity Framework that you want the Roles -> Operators relationship. Try adding this to your Role class.
public virtual ICollection<TDOperator> Operators { get; set; }

Categories

Resources