I write chat in C# with Entity Framework
This is my code
public class User
{
[Key]
public long id { get; set; }
public List<UserMessages> userMessages { get; set; }
}
public class UserMessages
{
[Key]
public long Id { get; set; }
public long ChatMateId { get; set; }
public string text { get; set; }
public DateTime? dateTime { get; set; }
}
Entity Framework code-first forced me to put on the Id field in UserMessages class attribute [Key] , I don't need this field at all because UserMessages is weak entity that will point to id of User
Can I delete long Id from sql table after ef create the table, without any problems?
No, you can't. EF requires that all tables have a [Key] on them, or it will blow up. Even when mapping to SQL Views (as I've learned the hard way, believe me).
In your case, you should actually be using a proper Foreign Key in that table also, like so:
public class UserMessages
{
[Key]
public long Id { get; set; }
[ForeignKey("User")]
public long UserId { get; set; }
public long ChatMateId { get; set; }
public string text { get; set; }
public DateTime? dateTime { get; set; }
public User User { get; set; }
}
Related
I'm working with EF core and I have a many-to-many relation between STUDENTS and SUBJECTS, like this:
public class StudentDetail
{
[Key]
[JsonPropertyName("Id")]
public int Id { get; set; }
[Required]
[Column(TypeName ="nvarchar(50)")]
[JsonPropertyName("Name")]
public string Name { get; set; }
[JsonPropertyName("StudentSubjects")]
public virtual IEnumerable<StudentSubject> StudentSubjects {get; set;}
}
public class SubjectDetail
{
[Key]
[JsonPropertyName("Id")]
public int Id { get; set; }
[Required]
[Column(TypeName = "nvarchar(20)")]
[JsonPropertyName("SubjectName")]
public string SubjectName { get; set; }
[Required]
[JsonPropertyName("Teacher")]
public virtual TeacherDetail Teacher { get; set; }
[JsonPropertyName("StudentSubjects")]
public IEnumerable<StudentSubject> StudentSubjects { get; set; }
}
public class StudentSubject
{
[JsonPropertyName("StudentId")]
public int StudentId { get; set; }
[JsonPropertyName("Student")]
public StudentDetail Student { get; set; }
[JsonPropertyName("SubjectId")]
public int SubjectId { get; set; }
[JsonPropertyName("Subject")]
public SubjectDetail Subject { get; set; }
[Required]
[Column(TypeName = "nvarchar(3)")]
[JsonPropertyName("Grade")]
public string Grade { get; set; }
}
I create my Databse using migrations, so after I did the migration, the database was created like this:
I need a query that bring me all the Subjects with their teacher and grade of an specific Student. I was tryng doing it like this:
var subjects = await _context.StudentSubject
.Include(s => s.Subject)
.Where(sid => sid.StudentId == student.Id)
.Select(st => st.Subject)
.Include(t => t.Teacher)
.ToListAsync();
But I'm getting an ERROR saying that I'm tryng to use Include(); on a non Queryable Entity. Anyone know what am I doing wrong?
Include will only work if you are having a link between two table and that is defined by keyword Virtual in C# classes. Please use public virtual ICollection instead of public IEnumerable and follow the link for more details. If you still wants to continue with same class then try using join in Linq queries.
I'm working on an ASP.net Web API application and would like to allow multiple users to have access to their own data without changing the database schema too much.
My tables look a little like this:
public class Asset
{
public string Name { get; set; }
[Required]
public int Id { get; set; }
public string AssetTag { get; set; }
public string Serial { get; set; }
public int Model { get; set; }
}
public class Organisation
{
[Required]
public int Id { get; set; }
[Required]
public int DefaultLocation { get; set; }
public location Location { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Contact { get; set; }
}
public class AssetModel
{
public string Name { get; set; }
[Required]
public int Id { get; set; }
public int CategoryId { get; set; }
public int ManufacturerId { get; set; }
public string ModelNumber { get; set; }
}
*fields omitted for brevity
Each user should be able to create their own assets / organisations / etc, but should not have access to any other users fields.
I'm yet to add authorization / authentication however I'm probably going to use token based auth as outlined here:
http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/
Should this be as easy as tacking each users GUID onto each column and applying some logic? Or will I need to completely re-design the database?
I need to create a price table system so I am going to create these three tables in my database.
PricingTable (ID, Name, ServiceID, Style)
PricingTablePackages (ID, PricingTable_ID, Title, Price, PricePerTime, Info, Flag, Link)
PricingTablePackagesFeatures (ID, PricingTablePackages_ID, Feature, Value, MoreInfo)
Here one PriceTable can hold more then one PricingTablePackages and one PricingTablePackage can hold more then one PricingTablePackagesFeature.
Is any way to design a better model? In a single database Table ?
I am going to create a MVC3 Model for those table so what is the best way to do this kind of DB Table in a MVC3 Model?
I would use public virtual variables for 'lazy-loading' values when you need them using Entity Framework:
(variable types may be off depending on exactly what you want for each variable)
public class PricingTablePackages
{
public int ID { get; set; }
public int PricingTableID { get; set; }
public virtual PricingTable PricingTable { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public decimal PricePerTime { get; set; }
public string Info { get; set; }
public bool Flag { get; set; }
public string Link { get; set; }
}
public class PricingTablePackagesFeatures
{
public int ID { get; set; }
public int PricingTableID { get; set; }
public virtual PricingTable PricingTable { get; set; }
public string Feature { get; set; }
public string Value { get; set; }
public string MoreInfo { get; set; }
}
public class PricingTable
{
public int ID { get; set; }
public string Name { get; set; }
public int ServiceID { get; set; }
public virtual Service Service { get; set; } // if there is a Service class
public string Style { get; set; }
}
I am very new to EF 4.1. I am getting the error in my Code First development in EF 4.1.
"Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF."
I searched in internet and understood abt the usage of the
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)].
But no use. I changed the option from Identity to None also. But no use.
You are trying to insert a new row into a table with an auto increment PK, you shouldnt be setting the ID property here when you try and add it to the DB.
I had this same error because I had defined a foreign key relationship the wrong way in my classes:
public partial class Student
{
[Key]
public int StudentId { get; set; }
public string StudentName { get; set; }
public int StudentAge { get; set; }
public int GradeNumber { get; set; }
public string LockerNumber { get; set; }
public string TeacherID { get; set; }
public string StudentComments { get; set; }
// Navigation properties
[ForeignKey("TeacherID")]
public virtual Teacher Teacher { get; set; }
public virtual GradeLevel GradeLevel { get; set; }
// the code below is incorrect, the StudentClass should have the StudentId
// as the FK entity:
[ForeignKey("StudentId")]
public virtual StudentClass StudentClass { get; set; }
}
The StudentClass class
public partial class StudentClass
{
[Key]
public int RowId { get; set; }
public int StudentId { get; set; }
public int ClassSubjectId { get; set; }
// Navigation properties
[ForeignKey("ClassSubjectId")]
public virtual ClassSubject ClassSubject { get; set; }
// this is the way the relationship should be defined:
[ForeignKey("StudentId")]
public virtual Student Student { get; set; }
}
First I'll show you what I do, and that there is. My project in ASP.NET MVC 3.
This is model for table Business.
[Table("Business")]
public class Business
{
[Key]
public long? BusinessId { get; set; }
public Int32 LegalTypeId { get; set; }
public Int16 BusinessTypeId { get; set; }
public Int64 OwnerId { get; set; }
public Int32 MainIndustryFieldId { get; set; }
public String NameNative { get; set; }
public String NameEnglish { get; set; }
public Byte[] Logo { get; set; }
public DateTime CreateDate { get; set; }
public virtual User Owner { get; set; }//It is Forign key with user table
}
[Table("User")]
public class User
{
[Key]
public Int64 UserId { get; set; }
public String UserName { get; set; }
public String LoweredUserName { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String LoweredEmail { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public String PasswordQuestion { get; set; }
public String PasswordAnswer { get; set; }
public Boolean IsApproved { get; set; }
public Boolean IsLocked { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime CreateDate { get; set; }
public virtual Business Bussines { get; set; }
}
when I want to add information:
user.Business = new Business
{
OwnerId = user.UserId,
LegalTypeId = business.LegalTypeId,
BusinessTypeId = business.BusinessTypeId,
MainIndustryFieldId = business.MainIndustryFieldId,
NameNative = business.NameNative,
NameEnglish = business.NameEnglish,
Logo = business.Logo,
CreateDate = DateTime.Now
};
ctx.SaveChanges();
I get the following error:
Cannot insert explicit value for identity column in table 'Business'
when IDENTITY_INSERT is set to OFF.
In database column identity specification business chose is Identity Yes.
Somebody can tell what to do.
Can you make sure that in your EDMX model, your BusinessId is set to be handled by the database (property StoreGeneratedPattern = Identity)?? Also: why is your primary key nullable (long?) - makes no sense whatsoever. Your primary key must never be null !
BusinessId can not be empty/null since you have not specified that it should be autogenerated by Sql Server (which Identity means).
Since you are using Code First to generate your database, just change to:
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long? BusinessId { get; set; }
override OnModelCreating in DbContext and add in it following Fluent API:
modelBuilder.Entity<Business>().HasRequired(m => m.Address).WithRequiredPrincipal(m => m.Business).WillCascadeOnDelete(true);