"Hide" column from database, but not View in Entity Framework - entity-framework-4.1

I am using a code-first methodology. I have created my own user model and membership provider. My model has some of the following fields:
[Table("mytable")]
public class MyUser
{
[Key]
public int UserId { get; set; } // Auto generated
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
public string ConfirmPassword { get; set; }
[Display(Name = "Your name/company name")]
public string Name { get; set; }
}
The problem is that I don't have a ConfirmPassword column in my database (for obvious reasons). How do I "hide" this from the database, but allow the view to be able to see an use it. Changing it to private hides it from the database, but the view doesn't like that.
How can I tell Entity Framework to ignore this field?

Mark the column you don't want to persist to database with [NotMapped] attribute.
Btw. this is typical example where you should think about differing between persisted entity and view model for your page = you should think about having two different classes.

Related

Model State Always true even when the required field is not sent

I am simply calling an API and passing an object as a parameter and everything works fine. But then i wanted to validate the model before going any further so i simply wrote [Required] above the fields i always wanted filled.
MODEL
public class Consent
{
public Consent()
{
}
public int Id { get; set; }
[Required]
public int FacilityId { get; set; }
public string Heading { get; set; }
public string Description { get; set; }
}
and validate the model state in controller like this
public ActionResult<int> AddConsent(Consent consent)
{
if(!ModelState.IsValid){
throw new CustomException("000-0000-000", "Validation failed");
}
//Further Code
}
By this i expected model state to be false when i don't send the facilityId when i call the api
JSON
{
"heading": "HeadingFromPostman5",
"description": "DiscriptiomFromPostman5"
}
but its still true . I know .Net core is allocating 0 to int value when null but how can i validate it then? Whats the work around for this?
Simply replace this line:
[Required]
public int FacilityId { get; set; }
With this:
[Required]
public int? FacilityId { get; set; }
The Required attribute works well for nullable reference objects. For primitives, when an instance is created, the default value (in this case 0 for int) is assigned for FacilityId, and hence the Required won't work. If you make the FacilityId as nullable int then the Required attribute will work fine.
[Required]
public int? FacilityId { get; set; }

Dotnet Core DB Scaffold creates additional Collections for Object

I have a Mysql Database and want to create a scaffold to try a data-first .net project. I got the scaffold to work, which was great, but it is creating these false Collections on my model objects for related tables.
For my coin object below, I only have the 5 fields on the top, but it is creating the collections to any of the tables where Coin is a foreign key. This is not really making any sense to me. I will never populate this data and cannot see any settings to stop this from happening.
public partial class Coin
{
public Coin()
{
LedgerTransactions = new HashSet<LedgerTransactions>();
Price = new HashSet<Price>();
TradeFeeCoin = new HashSet<Trade>();
TradeForCoin = new HashSet<Trade>();
TradeTradeCoin = new HashSet<Trade>();
}
[Column(TypeName = "int(11)")]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(5)]
public string Symbol { get; set; }
public byte? SortOrd { get; set; }
[Column(TypeName = "bit(1)")]
public bool? IsBaseCurrency { get; set; }
[InverseProperty("Coin")]
public ICollection<LedgerTransactions> LedgerTransactions { get; set; }
[InverseProperty("Coin")]
public ICollection<Price> Price { get; set; }
[InverseProperty("FeeCoin")]
public ICollection<Trade> TradeFeeCoin { get; set; }
[InverseProperty("ForCoin")]
public ICollection<Trade> TradeForCoin { get; set; }
[InverseProperty("TradeCoin")]
public ICollection<Trade> TradeTradeCoin { get; set; }
}
I created this table from a Code-First approach, and that model only had the 5 fields in it that I would expect. Am I doing something wrong?

Entity Framework in MY.SQL ASP.NET Core Angular project fails with MySqlException error in syntax near CONSTRAINT when trying to DropForeignKey

I am running a project using code first migrations. I have a big model and everything ran smoothly untill this happened. So part of the big picture was like looking this. Initial state model number one:
public class WebClient
{
public int Id { get; set; }
public string FirstName { get; set; }
public IList<Trade> Trades { get; set; }
public IList<Portfolio> Portfolios { get; set; }
public IList<Strategy> Strategies { get; set; }
[Required]
public string EMail { get; set; }
}
And the second model:
public class Strategy
{
public int Id { get; set; }
public string Name { get; set; }
public string ShortDesc { get; set; }
public string EntryRules { get; set; }
public string ExitRules { get; set; }
public IList<Trade> Trades { get; set; }
}
When I ran this migration to MYSQL database Entity Framework created a webClientId column in the strategies table and set it to be the foreign key for WebCLients.Id (for the id in the webclients table) and also created an index for that which is pretty cool.
After this I realized I forgot to input a relation to the webclient inside the strategy model. So I put two lines in and got this.
public class Strategy
{
public int Id { get; set; }
public string Name { get; set; }
public string ShortDesc { get; set; }
public string EntryRules { get; set; }
public string ExitRules { get; set; }
public IList<Trade> Trades { get; set; }
public virtual WebClient WebClient { get; set; } //new stuff
public int WebClientId { get; set; } //new stuff
}
For this Entity Framework suggested a following migrations which is a bit weird to start with.
migrationBuilder.DropForeignKey(
name: "FK_Strategies_WebClients_WebClientId",
table: "Strategies");
migrationBuilder.AlterColumn<int>(
name: "WebClientId",
table: "Strategies",
nullable: false,
oldClrType: typeof(int),
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_Strategies_WebClients_WebClientId",
table: "Strategies",
column: "WebClientId",
principalTable: "WebClients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
So it drops the old key to create a new one which is exactly the same apart from that it is not nullable. Ok well let's do it. However when I run a database update on that I get an error and I have no idea on how to deal with it.
MySql.Data.MySqlClient.MySqlException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CONSTRAINT FK_Strateg
ies_WebClients_WebClientId' at line 1
If I run the command with a --verbose flag I can catch the bit of SQL and see where it crashes...
ALTER TABLE Strategies DROP CONSTRAINT FK_Strategies_WebClients_WebClientId;
Has anyone come across this issue ? Will be real glad to hear any hints, Thanks!
Ok so the work around is like this. Seems to me MySQL doesn't understand:
ALTER TABLE Strategies DROP CONSTRAINT FK_Strategies_WebClients_WebClientId;
That is for SQL Server / Oracle / MS Access. More on this here
I just changed that line in the migrations to
migrationBuilder.Sql("ALTER TABLE Strategies DROP FOREIGN KEY FK_Strategies_WebClients_WebClientId;");
Everything updated fine after that. Result - use DROP FOREIGN KEY in MySql instead of DROP CONSTRAINT. No idea why that is not fized in the MySql Adapter for Entity Framework.
This is happening because Entity Framework doesn't understand that WebClientId is a foreign key so it is adding a new foreign key field for you. The Entity Framework convention for naming automatically inserted foreign key fields is TableName_Id,
Entity Framework Code First provides a set of data annotation attributes that can be applied on domain classes or the properties of domain classes.The ForeignKey attribute is used to specify which property is the foreign key in a relationship (ForeignKey Attribute specifies the foreign key for the Navigation property in Entity Framework).
Example:
public class Strategy
{
public int Id { get; set; }
public string Name { get; set; }
public string ShortDesc { get; set; }
public string EntryRules { get; set; }
public string ExitRules { get; set; }
public IList<Trade> Trades { get; set; }
public int WebClientId { get; set; } //Foreign Key property
[ForeignKey("WebClientId")]
public WebClient WebClient { get; set; } //Respective Entity
}
public class WebClient
{
public int Id { get; set; }
public string FirstName { get; set; }
[Required]
public string EMail { get; set; }
public IList<Trade> Trades { get; set; }
public IList<Portfolio> Portfolios { get; set; }
public IList<Strategy> Strategies { get; set; }
}
You can get more information from this link.

Razor, MVC4, #html.dropdownlistfor problems

I'm trying to create a drop down list that populates from a database. I have:
public class Employee
{
[Key]
public int Id { get; set; }
[Required]
public String FirstName { get; set; }
[Required]
public String LastName { get; set; }
[Required]
public String JobTitle { get; set; }
}
public class Project
{
[Key]
public int Id { get; set; }
[Required]
public String ProjectName { get; set; }
[Required]
public String CompanyName { get; set; }
}
public class ProjectHour
{
[Key]
public int Id { get; set; }
[Required]
public decimal Hours { get; set; }
[Required]
public DateTime Date { get; set; }
public virtual ICollection<Employee> employeeId { get; set; }
public virtual ICollection<Project> projectId { get; set; }
}
What I want is to create a form that will create new project hours associated with a project and an employee. I'm trying to use dropdownlists to display the employees and the projects on the create form. Obviously, I'm completely new at this, but what I have so far is:
[HttpPost]
public ActionResult CreateProjectHour(ProjectHour newProjectHour)
{
using (var db = new TimesheetContext())
{
IEnumerable<SelectListItem> emp = db.Employees
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.LastName
});
ViewBag.EmployeeId = emp;
db.ProjectHours.Add(newProjectHour);
db.SaveChanges();
}
return RedirectToAction("ProjectHourList");
}
}
And on the form:
#model TimesheetMVC.Models.ProjectHour
...
#Html.DropDownListFor(model => model.employeeId, (SelectList)ViewBag.EmployeeId)
Which is apparently horribly wrong. Any help would be much appreciated...!
Don't use the same name EmployeeId. You need 2 things to create a dropdown list in ASP.NET MVC: a scalar property that will hold the selected value and a collection property that will contain the possible values. But since you are using the ViewBag (which I totally recommend against) you could do the following:
ViewBag.Employees = emp;
and in your view:
#Html.DropDownListFor(
model => model.employeeId,
(IEnumerable<SelectListItem>)ViewBag.Employees
)
But as I said this is not at all an approach that I recommend. I recommend using view models. So define an IEnumerable<SelectListItem> property on your view model:
public IEnumerable<SelectListItem> Employees { get; set; }
and in your controller populate this view model property and then make your view strongly typed to the view model.
Or you could just do a
in the controller
SelectList selectList = new SelectList(db.Employees, "Id", "LastName");
ViewBag.EmployeeList = selectList;
and in the View
#Html.DropDownBoxFor(model => model.id_Employee, ViewBag.EmployeeList as SelectList)
I find this approach easier.
EmployeeId is an IEnumerable<SelectListItem>, not a SelectList.
Therefore, your cast cannot work.
You need to explicitly create a SelectList.

Issue when inserting Chinese data with code first and mysql

I've done a project in ASP.NET MVC 3 using Mysql. To create a database, I use code first ef 4.1. Some of the data I insert in my database is Chinese characters. When I insert the data, it appears with ????. I set my connectionString in my web config like this:
add name="mydbcontext" connectionString="server=localhost;user id=root; password=; database=mydbcontext; pooling=false; charset=utf8;" providerName="MySql.Data.MySqlClient"
But the problem's still there... This is the way I use to insert the data:
public class MyMenu {
public int Id { get; set; }
public string Home { get; set; }
public string About { get; set; }
public string AppForSmartphone { get; set; }
public string Games { get; set; }
public string Softwares { get; set; }
public string Language { get; set; }
public string News { get; set; }
public string Cart { get; set; }
}
public class MyDbContext : DbContext {
public DbSet<MyMenu> MyMenus { get; set; }
public MyDbContext()
: base("MyDbContext") {
}
}
private MyDbContext db = new MyDbContext();
MyMenu tmpmenu = new MyMenu {
About = 關於,
Id = 1,
Cart = 車,
News = 新聞,
AppForSmartphone = 應用程序的智能手機,
Games = 遊戲,
Softwares = 軟件,
Home = 家,
Language = ""
};
db.MyMenus.Add(tmpmenu);
db.SaveChanges();
Can someone help me?
There is no Issue in your code.You just need to check the DataType of the column in which you are saving the data which is in Chinese.I guess you have used varchar() , rather you should be using nvarchar().
I had the same issue a day back. And changing the datatype to nvarchar() fixed my issue.
MySql does support multilingual.
Changing the DataType should fix your issue.
Regards.