I am using MVC4 ,T4 Scaffolding and EF5.
I Created a model,
namespace wbtest.Models
{
[Table(name: "Pay_Employees_Mst", Schema = "Test")]
public class Employee
{
public int EMPLOYEE_ID { get; set; }
public string EMPLOYEE_CODE { get; set; }
}
}
I need to get the annotation of table name "Pay_Employees_Mst" for db context .Currently getting ModelName Employee.
Please Help.
I got it through,
String entityName1 = (context as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext
.CreateObjectSet<Employee>()
.EntitySet.Name;
Related
I have an SQlite table with 4 Columns in Xamarin app.
I've already inserted 3 columns and now i need an update statement to Update 4th column with some values using for loop.
(OR)
Please suggest any better/other method to do the same.
Do you want to update the record in the sqlite DB?
If so you can use this model to update the record in the DB.prijem.BCode is PrimaryKey, we set the type of PrimaryKey is int and AutoIncrement, So, if the model's PrimaryKey is not equal zero, this record stored in the DB, we can update this record by the Model.
readonly SQLiteAsyncConnection _database;
public PrijemDatabase(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<Prijem>().Wait();
}
public Task<int> SavePrijemAsync(Prijem prijem)
{
if (prijem.BCode != 0)
{
return _database.UpdateAsync(prijem);
}
else
{
return _database.InsertAsync(prijem);
}
}
Here is my model.
public class Prijem
{
[PrimaryKey, AutoIncrement, Unique]
public int BCode { get; set; }
public string Name { get; set; }
public string FirmName { get; set; }
public string ItemCode { get; set; }
public string Count { get; set; }
}
Here is link about how to execute CRUD, you can refer to it.
https://learn.microsoft.com/en-us/xamarin/get-started/quickstarts/database?pivots=windows
Here is a demo about it.
https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/getstarted-notes-database/
I am using MVC database first approach and created one .edmx file.
Now my all the tables are available in this model.tt file.
I have also defined some dataannotation on those fields of table.
But What I have noticed that when ever I tried to update this model then value of dataanotation will be lapse.
Any thoughts please.
Yes it's kinda funny how much you read about annotations but you can't actually use them because they get overwritten.
This is what I found to help me
http://www.ozkary.com/2015/01/add-data-annotations-to-entity.html
also this
https://learn.microsoft.com/en-us/previous-versions/aspnet/ee256141(v=vs.98)
I don't pretend to understand it but here's a join the dots guide.
An example generated EF class looks like this:
public partial class Employee
{
public int Emp_ID { get; set; }
public string Emp_Name { get; set; }
public Nullable<System.DateTime> Commencement_Date { get; set; }
}
Definitely do not edit this.
Instead you create a seperate class file (I called mine metadata.cs and put it in the Models folder) with this in it:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace MyProject.Models
{
[MetadataType(typeof(EmployeeMD))] // new name for your metadata class
public partial class Employee // same name as your EF generated class
{
// Nothing in here
}
internal sealed class EmployeeMD // your metadata class
{
[Required]
[StringLength(50, MinimumLength = 2, ErrorMessage = "Name required")]
public string Emp_Name { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Commencement_Date { get; set; }
}
}
I am trying to implement view model to get the data from multiple table. However, I am getting the following error
InvalidOperationException: The entity type 'RoleManagement.Models.RolePermissionsViewModel' requires a key to be defined.
Below is my view model
public class RolePermissionsViewModel
{
public List<LMS_RolePermissions> RolePermissions { get; set; }
public List<LMS_UserPermissions> UserPermissions { get; set; }
}
Where LMS_RolePermissions and LMS_UserPermissions are two different tables in the database. Basically I want to get the data from these two tables in view model. To get the data I have written below code
RolePermissionsViewModel rolemodel = new RolePermissionsViewModel
{
RolePermissions = dbContext.RolePermissions.ToList(),
UserPermissions = dbContext.UserPermissions.ToList()
};
and DBContext class
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<LMS_LocLanguage> LMS_LocLanguage { get; set; }
public DbSet<LMS_Permissions> Permissions { get; set; }
public DbSet<LMS_RolePermissions> RolePermissions { get; set; }
public DbSet<LMS_UserPermissions> UserPermissions { get; set; }
public DbSet<RolePermissionsViewModel> RoleUserPermission { get; set; }
}
I do not want to Key to be defined and table should NOT be created.
How can I solve this problem ?
it is advised to place seperately your domainmodels and viewmodels. all tables in the applicationcontext are created by entity framework convention if if i use DbSet<myclass> or mention it in another class that used with Dbset. your answer should be excluding types with data annotations NotMapped and with fluent api modelbuilder.ignore<RolePermissionsViewModel>();. (of course,you will remove DbSet firstly. if i read and understand correctly, you say to your codes "please dont create this,i beg on you" after you command database to set.)
I'm getting the following error when I try to insert a new row in one of my relational tables. I have the following two models:
public class CompanyCredit
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int creditId { get; set; }
public int planCredit { get; set; }
public DateTime? PlanCreditExpirationDate { get; set; }
}
And
public class CompanyInformation
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[Required]
[DisplayName("Company Name:")]
public string companyName { get; set; }
public string timeZone { get; set; }
//navigation Properties
public virtual CompanyCredit Credits { get; set; }
}
And this Relation in the dbContext
modelBuilder.Entity<CompanyInformation>().HasOptional(e => e.Credits);
I'm trying to add a record inside CompanyCredit table like so:
if (_company.Credits == null)
{
var _credits = new CompanyCredit();
_credits.planCredit = 200;
_credits.PlanCreditExpirationDate = System.DateTime.UtcNow.AddMonths(1);
_company.Credits = _credits;
repo.InsertOrUpdate(_company, User.Identity.Name);
}
And Finally Insert or update just marks Company as changed and _credit as added like so:
_db.Entry(_credits).State = System.Data.EntityState.Added;
_db.Entry(Company).State = System.Data.EntityState.Modified;
_db.SaveChanges();
When this runs I get the following Error that I just can't seem to find the reason to.
Cannot insert the value NULL into column 'creditId', table 'Project.dbo.CompanyCredits'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Thank in advanced for your help.
I found the problem was in the attribute [DatabaseGenerated(DatabaseGeneratedOption.Identity)] this should have been [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
I thought I would post this so others might benefit from it.
Could you please try reversing the order of entity state modification, just before the saveChanges call
_db.Entry(Company).State = System.Data.EntityState.Modified;
_db.Entry(_credits).State = System.Data.EntityState.Added;
_db.SaveChanges();
I'm using a context generated from an EDMX for a mvc3 webapp. I'm getting a NULL insert fails error on an entity
[Serializable]
[DataContract(IsReference = true)]
[EdmEntityType(NamespaceName = "Model", Name = "Thing")]
public class Thing: EntityObject
{
public RolloverEntry();
[DataMember]
[EdmScalarProperty(EntityKeyProperty = true, IsNullable = false)]
public int id { get; set; }
[SoapIgnore]
[EdmRelationshipNavigationProperty("Model", "FK_ThingStep1", "Step1")]
[DataMember]
[XmlIgnore]
public EntityCollection<Step1> Step1 { get; set; }
[SoapIgnore]
[EdmRelationshipNavigationProperty("Model", "FK_ThingStep2", "Step2")]
[XmlIgnore]
[DataMember]
public EntityCollection<Step2> Step2 { get; set; }
public static Thing CreateThing(int id);
}
Data access to other parent-child relationships are working and persisted correctly - I can't seem to find what's wrong with this table tho - any ideas appreciated
Exception Recieved:
{"Cannot insert the value NULL into column 'id', table 'myapp.dbo.Thing'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
Thanks
I'm guessing you need some sort of hint in your model that the database should generate the ids for the id column. You might want to see if StoreGeneratedPattern is set to Identity for your model property id or something along those lines.