problem custom primary key name - sql-server

I have an existing database and im having trouble using my table primary key "useridPK".
I'd like to use the default "ID" as an alias of my useridPK.
My models are setup like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq.Mapping;
using System.Data.Linq;
using System.Data.Entity;
using System.Diagnostics;
namespace myPROJECT.Models
{
[Table(Name="AskUsers")]
public class AskUser
{
[Column(Name="useridPK",IsPrimaryKey=true,IsDbGenerated=true)]
public Int32 ID { get; private set; }
[Column]
public int roleidFK { get; set; }
[Column]
public string username { get; set; }
[Column]
public string password { get; set; }
[Column]
public DateTime datecreated { get; set; }
[Column]
public string firstname { get; set; }
[Column]
public string lastname { get; set; }
}
public class myPROJECT_DBContext : DbContext
{
public DbSet<AskUser> AskUsers { get; set; }
}
}
It gives the error:
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'ID'.
My controller code:
public ActionResult Stuff()
{
var uu = from x in db.AskUsers
select x;
return View(uu.ToList());
}
I'm not really sure if this part:
[Column(Name="useridPK",IsPrimaryKey=true,IsDbGenerated=true)]
is deprecated in MVC3?
Thanks a lot
:)

According to this article: http://blogs.msdn.com/b/adonet/archive/2010/12/06/ef-feature-ctp5-released.aspx
EF Feature CTP5 Released! 6 Dec 2010 9:00 PM
The full list of data annotations supported in CTP5 is;
ColumnAttribute :
Placed on a property to specify the column name, ordinal & data type
If you are using a pre-CTP5 version of EF, perhaps ColumnAttribute is not supported in that version.

Related

Why I couldn't call Model inside my Controller

I have one problem and I have no idea what to do. I am try couple of method but nothing works for me. I have model Patient
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace BergClinic.Models
{
public class Patient
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name ="First Name")]
[MaxLength(50)]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[MaxLength(50)]
public string LastName { get; set; }
[Required]
[Display(Name = "Date of Birth")]
public DateTime DateOfBirth { get; set; }
[Display(Name = "Address")]
[MaxLength(50)]
public string Address { get; set; }
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Display(Name = "Gender")]
public PatientGender Gender { get; set; }
}
public enum PatientGender
{
[Display(Name ="Male")]
Male,
[Display(Name = "Female")]
Female,
Unknown
}
}
And IPatientRepository and PatientRepository which contains following logic:
using BergClinic.DataAccess.Data;
using BergClinic.DataAccess.Repository.IRepository;
using BergClinic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BergClinic.DataAccess.Repository
{
public class PatientRepository : Repository<Patient>, IPatientRepository
{
private readonly ApplicationDbContext _db;
public PatientRepository(ApplicationDbContext db) : base(db)
{
_db = db;
}
public void Update(Patient patient)
{
var objDb = _db.Patients.FirstOrDefault(s => s.Id == patient.Id);
if (objDb != null)
{
objDb.FirstName = patient.FirstName;
objDb.LastName = patient.LastName;
objDb.DateOfBirth = patient.DateOfBirth;
objDb.Address = patient.Address;
objDb.PhoneNumber = patient.PhoneNumber;
objDb.Gender = patient.Gender;
_db.SaveChanges();
}
}
}
}
And here is IPatientRepository which containt Update method
using BergClinic.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace BergClinic.DataAccess.Repository.IRepository
{
public interface IPatientRepository : IRepository<Patient>
{
void Update(Patient patient);
}
}
Once I creat this in my Admin Area in PatientController I want to initialize object Patient but I couldn't. I want to create Upsert method for Update and Insert Patient but whatever I type It doesn't see my model only what it is see is Patient workspace
'Patient' is a namespace but is used like a type
using BergClinic.DataAccess.Repository.IRepository;
using Microsoft.AspNetCore.Mvc;
using BergClinic.Models;
namespace BergClinic.Areas.Admin.Controllers
{
[Area("Admin")]
public class PatientController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public PatientController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IActionResult Index()
{
return View();
}
public IActionResult Upsert(int? Id)
{
Patient patient = new Areas.Patient
return View();
}
#region API_CALLS
[HttpGet]
public IActionResult GetAll()
{
var patient = _unitOfWork.Patient.GetAll();
return Json(new { data = patient });
}
#endregion
}
}
Just to notice I use RepositoryPatten and thee way arhitecture. I try to restart Visual Studio but seem nothing happened, I try to remove Project Reference and try to add again, but noting happened againg.
Here is couple of sceen of my ProjectStructures which you can check:

Insert Identity using Microsoft.EntityFramework.Sqlite.Core

How would I go about modifying my Add method so it inserts a new identity each time it performs an insert. Is there a clean LINQ syntax way to do this without using hardcoded SQL?
Here is the method that saves the data to the SQLite table via Entity Framework
public static void Add(CreditCardTableData creditCard)
{
using var context = new SqliteContext();
var entity = context.CreditCards.Add(creditCard);
entity.State = EntityState.Added;
context.SaveChanges();
}
Here is the class representing the table data:
using System;
using System.Collections.Generic;
using System.Text;
namespace DebtRefresh.Domain.Data.DatabaseTables
{
public class CreditCardTableData
{
public int CreditCardTableId { get; set; }
public int CreditCardType { get; set; }
public string AccountNickName { get; set; }
public float CreditLine { get; set; }
public float OwingBalance { get; set; }
}
}
use DatabaseGenerated Attribute on the Primary key Property
Identity: ValueGeneratedOnAdd
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CreditCardTableId { get; set; }

How to had foreign key

(lol).
For who I know I been working (for training) on a pokemon database.
I have a problem with my database creation.
I have 18 different types :
"Acier"
"Combat"
"Dragon"
"Eau"
"Electrik"
"Fee"
"Feu"
"Glace"
"Insecte"
"Normal"
"Plante"
"Poison"
"Psy"
"Roche"
"Sol"
"Spectre"
"Tenebre"
"Vol"
A pokemon can have one OR two types :
Example :
Pickachu type Electrik.
Bulbizarre type Plante and Poison.
I try to use foreign key for create my database but I don't know how to do it please help.
I have a Pokemon model class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Pokemon.Models
{
[Table("Pokemons")]
public class Pokemon
{
[Key]
public int PokemonId { get; set; }
[StringLength(30)]
public string PokemonName { get; set; }
[StringLength(30)]
public string PokemonUsName { get; set; }
[StringLength(30)]
public string PokemonDeName { get; set; }
[StringLength(30)]
public string PokemonJpName { get; set; }
public string PokemonDescription { get; set; }
public int PokemonRate { get; set; }
public string PokemonImage { get; set; }
public int PokemonTypeId { get; set; }
[ForeignKey("PokemonType")]
public virtual PokemonType PokemonType { get; set; }
}
}
And a PokemonType model class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Pokemon.Models
{
[Table("PokemonTypes")]
public class PokemonType
{
[Key]
public int TypeId { get; set; }
[StringLength(8)]
public string Type { get; set; }
public virtual ICollection<Pokemon> Pokemons { get; set; }
}
}
I hope I asked my question clearly.
I want to make a pokemon "Bulbizarre" whit Type1Id = 7 //7for plante
And type2Id = 24 //24 for poison.
But some of them have only one type : type1Id 13 //13 for Electrik
and Type2Id = null. //because no second type.
Table PokemonTypes screen from databse
I made it !
I made databse first and scaffold it!
Database diagram
this make me 3 model class with everythings correct inside
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataModels.Models
{
public partial class Pokemons
{
public Pokemons()
{
PokemonsPokemonTypes = new HashSet<PokemonsPokemonTypes>();
}
public int Id { get; set; }
public int Num { get; set; }
[Required]
[StringLength(30)]
public string Name { get; set; }
[StringLength(30)]
public string UsName { get; set; }
[StringLength(30)]
public string JpName { get; set; }
public int? Rate { get; set; }
public string Description { get; set; }
public string Image { get; set; }
[StringLength(50)]
public string Kind { get; set; }
public double? Height { get; set; }
public double? Weight { get; set; }
[InverseProperty("Pokemon")]
public virtual ICollection<PokemonsPokemonTypes> PokemonsPokemonTypes { get; set; }
}
}
using System.ComponentModel.DataAnnotations.Schema;
namespace DataModels.Models
{
public partial class PokemonsPokemonTypes
{
public int PokemonId { get; set; }
public int TypeId { get; set; }
[ForeignKey("PokemonId")]
[InverseProperty("PokemonsPokemonTypes")]
public virtual Pokemons Pokemon { get; set; }
[ForeignKey("TypeId")]
[InverseProperty("PokemonsPokemonTypes")]
public virtual PokemonTypes Type { get; set; }
}
}
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataModels.Models
{
public partial class PokemonTypes
{
public PokemonTypes()
{
PokemonsPokemonTypes = new HashSet<PokemonsPokemonTypes>();
}
public int Id { get; set; }
[StringLength(8)]
public string Type { get; set; }
[InverseProperty("Type")]
public virtual ICollection<PokemonsPokemonTypes> PokemonsPokemonTypes { get; set; }
}
}
This works pretty well!
One Product (Pokemon) can have Multipke Categories (Type).
There is one bug in your code listing, The [ForeignKey] attribute can be put on the foreign key property or the navigation property, but if on the Navigation property it needs to be set to point to the FK field name. (PokemonTypeId)
Two options to support more than one pokemon type:
If a Pokemon can have 1 or 2, but at max 2 types, then you can add two PokemonType references to the Pokemon. For example:
public int PrimaryPokemonTypeId { get; set; }
[ForeignKey("PrimaryPokemonTypeId")]
public virtual PokemonType PrimaryPokemonType { get; set; }
public int? SecondaryPokemonTypeId { get; set; }
[ForeignKey("SecondaryPokemonTypeId")]
public virtual PokemonType SecondaryPokemonType { get; set; }
If you can possibly refer to more than 2 types then you can adopt a many-to-many relationship rather than a 1 to many relationship. You can restrict the # of related types in code to two if you wish, but the data schema will support any number of types on a Pokemon.
A Pokemon would hold a collection of types. This means introducing a linking table. I.e. A PokemonTypePokemon.
If this is EF Core then you need to define the linking table:
public class Pokemon
{
// ... Pokemon fields...
public virtual ICollection<PokemonTypePokemon> PokemonTypes { get; set; } = new List<PokemonTypePokemon>();
}
public class PokemonType
{
// Classifications...
public virtual ICollection<PokemonTypePokemon> Pokemon { get; set; } = new List<PokemonTypePokemon>();
}
public class PokemonTypePokemon
{
public virtual Pokemon { get; set; }
public virtual PokemonType { get; set; }
}
This will require a little wiring up in the DbContext to associate the linking table. In the DbContext's OnModelCreating handler...
// EF Core
modelBuilder.Entity<Pokemon>()
.HasMany(x => x.PokemonTypes)
.WithOne(x => x.Pokemon)
.HasForeignKey("PokemonId");
modelBuilder.Entity<PokemonType>()
.HasMany(x => x.Pokemon)
.WithOne(x => x.PokemonType)
.HasForeignKey("PokemonTypeId");
You will likely need to configure the PK for the PokemonTypePokemon table as well to use a composite key on PokemonId & PokemonTypeId.
With EF6 you can map a HasMany().WithMany(), without needing the map the joining table in many cases. This should give you some idea where to start with the mapping change and joining table. Do a bit of Google-fu on EF Many-to-Many to refine.

SqlException: Invalid column name 'ClientId1'

Got a table in SQL Server with a ClientId (int, foreign key). Run the program, everything fine.
Renamed the column to ClientID (capitals ID). After importing the model ASP.NET MVC Core
Scaffold-DbContext "Server=DESKTOP-XYZ;Database=MyDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force
and run the program, I get the error Invalid column name 'ClientId1'.
In the whole project ClientId1 is not found
Rebuild does not work
Adding ClientId1 (temporary) to the database will give an error about 'ClientId2', etc. ...
Drop create database won't work
Exit/Start VS2017 has no effect
SQL Server profiler shows a statement with 'ClientId1'
Get the error on a simple statement (for the table I made the change):
var projectList = await context.Project.ToListAsync();
The SQL Server profiler shows
SELECT [p].[ID], [p].[ClientID], [p].[ClientId1], [p].[Description], [p].[ExpirationDate], [p].[ImageDirectory], [p].[Name], [p].[Price], [p].[Size], [p].[StartDate], [p].[StatusID], ...
FROM [Project] AS [p]
The (correctly) generated Project class looks like (there is no ClientId1):
...
public int Id { get; set; }
public int? ClientId { get; set; }
public string Description { get; set; }
public DateTime ExpirationDate { get; set; }
public string ImageDirectory { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Size { get; set; }
public DateTime StartDate { get; set; }
public int StatusId { get; set; }
...
How to solve this, thanks for any help!
The problem has nothing to do with the renaming of the column. In about the same period a property was added to the NOT generated partial Client class:
public partial class Client
{
...
public List<Project> ProjectList { get; set; }
...
}
This seems to confuse Linq. Needed is an extra [NoMapped] DataAnnotation. So the following code will work.
public partial class Client
{
...
[NoMapped]
public List<Project> ProjectList { get; set; }
...
}

I'm using EF in my application. I try to save\insert a new record to a Patient View

I made a view in SQL server and then added to to my edmx file in visual studio 2012 I then went to POST it on Postman and got this runtime error.
Unable to update the EntitySet 'ViewPatient' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
//Controller action code namespace MvcWebAPI.Models
{
using System;
using System.Collections.Generic;
public partial class ViewPatient
{
public int PatientID { get; set; }
public int MedicationID { get; set; }
public int GPID { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
public System.DateTime DOB { get; set; }
public string Medication { get; set; }
public string Alergies { get; set; }
public string MedicationHistory { get; set; }
}
}
You need a primary key on the view. http://blogs.msdn.com/b/alexj/archive/2009/09/01/tip-34-how-to-work-with-updatable-views.aspx

Resources