I am creating ASP.Net MVC WebApi to share my data to bank. In this regard i have created an SQL View bit when i am testing my WebApi it is giving an 'System.OutOfMemoryException' error because i have more the 1 million record in SQL View.
My Code is given below:-
This is my controller
public class InvoiceController : ApiController
{
public IEnumerable<VBank_invoice> Get()
{
using (kmcEntities entities = new kmcEntities())
{
return entities.VBank_invoice.ToList();
}
}
public VBank_invoice Get(string consumer)
{
using (kmcEntities entities = new kmcEntities())
{
return entities.VBank_invoice.FirstOrDefault(e => e.consumer_no == consumer);
}
}
}
My SQL View Class
public partial class VBank_invoice
{
public int sno { get; set; }
public string consumer_no { get; set; }
public string consumer_name { get; set; }
public string consumer_address { get; set; }
public string billing_month { get; set; }
public Nullable<decimal> current_Charges { get; set; }
public Nullable<decimal> outstanding_Arrears { get; set; }
public Nullable<decimal> Arrears_15 { get; set; }
public Nullable<decimal> part_payment_arrears { get; set; }
public string billing_period_code { get; set; }
public string consumer_checkdigit { get; set; }
public Nullable<System.DateTime> due_date { get; set; }
}
This is my Model.Context.cs File
public partial class kmcEntities : DbContext
{
public kmcEntities()
: base("name=kmcEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<VBank_invoice> VBank_invoice { get; set; }
}
I believe you need to be serialize object model using the select query.
public class InvoiceController : ApiController
{
public IEnumerable<VBank_invoice> Get()
{
using (kmcEntities entities = new kmcEntities())
{
return entities.VBank_invoice.select(m => new {
m.sno, m.consumer_no,m.consumer_name, m.consumer_address,
m.billing_month, m.current_Charges, m.outstanding_Arrears,
m.Arrears_15, m.part_payment_arrears, m.billing_period_code,
m.consumer_checkdigit, m.due_date }).ToList();
}
}
}
Related
How do I map table value functions in Code with Entity Framework 6.3? I'm trying to a DB Context in code with an existing database, because EDMX is currently not supported in ASP.NET Core 3. I've tried setting up my DbContext clasee as below. I can successfully query the Grade table. But when I try to query my function "fn_GetCatgeories", I get the following error: No EdmType found for type 'WebApplication6.Data.ApplicationContext+fn_GetCategories'.
public class ApplicationContext : DbContext
{
public ApplicationContext(string cstr)
: base(cstr)
{
Database.SetInitializer<ApplicationContext>(null);
}
[Table("Grade")]
public class Grade
{
[Key]
public string Grade_ID { get; set; }
public string SchoolType { get; set; }
public int Sortorder { get; set; }
}
public partial class fn_GetCategories
{
public int Category_ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<bool> Active { get; set; }
public Nullable<System.DateTime> Month { get; set; }
public Nullable<int> Order { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new FunctionsConvention<ApplicationContext>("dbo"));
base.OnModelCreating(modelBuilder);
}
[DbFunction("ApplicationContext", "fn_GetCategories")]
public IQueryable<fn_GetCategories> GetCategories(Nullable<System.DateTime> month)
{
var monthParameter = month.HasValue ?
new ObjectParameter("Month", month) :
new ObjectParameter("Month", typeof(System.DateTime));
return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<fn_GetCategories>(string.Format("[0].{1}", GetType().Name, "[fn_GetCategories](#Month)"), monthParameter);
}
// DbSets here
public DbSet<Grade> Grades { get; set; }
}
This works:
public class ApplicationContext : DbContext
{
public ApplicationContext(string cstr)
: base(cstr)
{
Database.SetInitializer<ApplicationContext>(null);
}
[Table("Grade")]
public class Grade
{
[Key]
public string Grade_ID { get; set; }
public string SchoolType { get; set; }
public int Sortorder { get; set; }
}
public partial class fn_GetCategories_Result
{
[Key]
public int Category_ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<bool> Active { get; set; }
public Nullable<System.DateTime> Month { get; set; }
public Nullable<int> Order { get; set; }
}
// DbSets here
public DbSet<Grade> Grades { get; set; }
public DbSet<fn_GetCategories_Result> fn_GetCategoriesSet { get; set; }
public List<fn_GetCategories_Result> fn_GetCategories(DateTime month)
{
var m = new SqlParameter("Month", DateTime.Now);
return this.fn_GetCategoriesSet.SqlQuery("select * from dbo.fn_GetCategories(#month)", m).ToList();
}
I am trying to ignore a class property when inserting data to database using metadata for the class but it is not working. I am using using EF 6. I have tried both the metadata and partial class are in the same assembly as the classes generated by EF
[NotMapped] and [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
Used a internal sealed class (for metadata) inside my partial class
namespace XeroDataStore.XeroDatabase
{
[MetadataType(typeof(TempAddressMetadata))]
public partial class TempAddress
{
}
[MetadataType(typeof(TempContact.TempContactMetadata))]
public partial class TempContact
{
internal sealed class TempContactMetadata
{
[NotMapped]
public Nullable<System.DateTime> UploadDate { get; set; }
}
}
}
namespace XeroDataStore.XeroDatabase
{
public class TempAddressMetadata
{
[NotMapped]
public Nullable<System.DateTime> UploadDate { get; set; }
}
}
EF Generated Class
namespace XeroDataStore.XeroDatabase
{
public partial class TempAddress
{
public int RowId { get; set; }
public int ClientID { get; set; }
public System.Guid ContactID { get; set; }
public string AddressType { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string AddressLine4 { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string AttentionTo { get; set; }
public Nullable<System.DateTime> UploadDate { get; set; }
public virtual TempContact TempContact { get; set; }
}
}
What am I missing here?
Do it using Fluent API to make sure your model classes are POCO and have nothing to do with the data access.
In your data context, OnModelCreating methoed, use the following code to ignore the property
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TempContact>().Ignore(a => a.UploadDate );
}
How i could add records to my database , with relation many-to-many in ASP.NET MVC 6 ?
I tried like that, but it's wrong
[HttpPost]
public IActionResult addpersons(Person pers)
{
var ourdoc = db.Documents.FirstOrDefault(p => p.Documentid == docselected);
ourdoc.DocPers.Add(ourdoc);
db.SaveChanges();
return Content("s");
}
Listings of my model files :
DocContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace TDS_1_ASPNETMVC6.Models
{
public class DocPer
{
public int Documentid { get; set; }
public Document Document { get; set; }
public int Personid { get; set; }
public Person Person { get; set; }
}
public class DocContext : DbContext
{
public virtual DbSet<Document> Documents { get; set; }
public virtual DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DocPer>()
.HasKey(t => new
{
t.Documentid,
t.Personid
});
modelBuilder.Entity<DocPer>()
.HasOne(pt => pt.Document)
.WithMany(p => p.DocPers)
.HasForeignKey(pt => pt.Documentid);
modelBuilder.Entity<DocPer>()
.HasOne(pt => pt.Person)
.WithMany(t => t.DocPers)
.HasForeignKey(pt => pt.Personid);
}
}
}
Documents.cs
using System.Collections.Generic;
namespace TDS_1_ASPNETMVC6.Models
{
public class Document
{
public int Documentid { get; set; }
public string Name { get; set; }
public string Props { get; set; }
public List<DocPer> DocPers { get; set; }
}
}
Person.cs
using System.Collections.Generic;
namespace TDS_1_ASPNETMVC6.Models
{
public class Person
{
public int Personid { get; set; }
public string Iname { get; set; }
public string Fname { get; set; }
public string Oname { get; set; }
public string Email { get; set; }
public List<DocPer> DocPers { get; set; }
}
}
First, your controller is not checking for null; what if var ourdoc = db.Documents.FirstOrDefault(p => p.Documentid == docselected); is null? So check for null first :)
Also ourdoc.DocPers.Add(ourdoc); must be changed to ourdoc.DocPers.Add(new DocPer {Person = person});
Second, to create a many-to-many I suggest you to remove the DocPer table and map it "behind", like this:
public class Document
{
public Document()
{
Persons = new List<Person>();
}
public int Documentid { get; set; }
public string Name { get; set; }
public string Props { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
public class Person
{
public Person()
{
Documents = new List<Document>();
}
public int Personid { get; set; }
public string Iname { get; set; }
public string Fname { get; set; }
public string Oname { get; set; }
public string Email { get; set; }
public virtual ICollection<Document> Documents { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Document>()
.HasMany<Person>(s => s.Persons)
.WithMany(c => c.Documents)
.Map(cs =>
{
cs.MapLeftKey("Documentid");
cs.MapRightKey("Personid");
cs.ToTable("DocPer");
});
}
DocPer table will be managed by the EF without exposing it. Check this site for more details. This guide will apply to EF6 only, not EF7 (which does not support many-to-many yet, for that support check this link). BTW, EF7 is still is not stable yet, so is possibile that this support will be offered in the future, but no one knows yet.
Im having troubles with an application. I have a MVC application that query a database (and some webservices) and return me information in JSON. In My Local Machine works like a charm but when I upload it to the webserver I get this error:
"Error getting value from '_owner' on 'System.Data.Objects.DataClasses.RelationshipManager'."
(You can see the whole error page in http://canedroid.com/mvc/api/requests/getlastcheckins)
I tried disabling proxies and lazy loading with:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.Configuration.LazyLoadingEnabled = false;
base.Configuration.ProxyCreationEnabled = false;
}
And nothing happens.
Model:
namespace CaneDroid.MVCApp.Models
{
public class CaneDroidContext : DbContext,ICaneDroidDataSource
{
public CaneDroidContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.Configuration.LazyLoadingEnabled = false;
base.Configuration.ProxyCreationEnabled = false;
}
public DbSet<Checkin> mdlCheckins { get; set; }
public DbSet<configAndroid> configAndroid { get; set; }
IQueryable<Checkin> ICaneDroidDataSource.Checkins
{
get { return mdlCheckins; }
}
}
public class Checkin
{
public Checkin()
{
visto = false;
}
[Key,DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public virtual int Id { get; set; }
[Required]
public virtual string fsqCheckinId { get; set; }
public virtual string text { get; set; }
public virtual string usrId { get; set; }
public virtual string usrFrstName { get; set; }
public virtual string usrLstName { get; set; }
public virtual string venueId { get; set; }
public virtual string venueName { get; set; }
public virtual string venueAddress { get; set; }
public virtual string venueCrossStreet { get; set; }
public virtual string venueLat { get; set; }
public virtual string venueLng { get; set; }
public virtual string venueCity { get; set; }
public virtual bool visto { get; set; }
}
public class configAndroid
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public virtual int Id { get; set; }
public string key { get; set; }
public bool value { get; set; }
}
}
Action in controller:
public R getLastCheckins()
{
var responseJson = R.getLastCheckins(db);
return responseJson;
}
public static R getLastCheckins(CaneDroidContext db)
{
var cache = db.mdlCheckins.OrderByDescending(q => q.Id).Take(10);
return new R(cache, null, null, null, null, null);
}
I don't know what else can I do.
Nevermind. I found the solution. The problem was the Context variable.
private static CaneDroidContext db = new CaneDroidContext();
When I modified it and made it static everything started to work normally.
I am using DB context approach in my asp.net mvc 4 test project.
Here are my domain classes
Category.cs
public class Categroy
{
public virtual int Id { get; set; }
public virtual string CategoryName{ get; set; }
public virtual ICollection<Post> Post{ get; set; }
}
Post.cs
public class Post
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Description { get; set; }
}
IPostsDateSource.cs
public interface IPostsDataSource
{
IQueryable<Category> Categories{ get; }
IQueryable<Post> Posts { get; }
void Save();
}
PostsDB.cs
public class PostsDB:DbContext,IPostsDataSource
{
public PostsDB():base("DefaultConnection")
{
}
public DbSet<Category> Categories{ get; set; }
public DbSet<Post> Posts{ get; set; }
void IPostsDataSource.Save()
{
SaveChanges();
}
IQueryable<Category> IPostsDataSource.Categories
{
get { return Categories; }
}
IQueryable<Post> IPostsDataSource.Posts
{
get { return Posts; }
}
}
I am using StructureMap for mapping
IoC.cs
...
x.For<IPostsDataSource>().HttpContextScoped().Use<PostsDB>();
...
In my HomeController I am
private IPostDataSource _db;
public HomeController(IAdsDataSource db)
{
_db = db;
}
I can retrieve all the posts by _db.Posts
public ActionResult Index()
{
var Posts= _db.Posts;
ViewBag.Posts = Posts;
return View();
}
The problem is what query should I write in order to retrieve all posts from a specific categrory
If a category has a collection of Posts, then Post entity should have a CategoryID property. You can query base on that CategoryID.
Otherwise you can query the category and retrieve the corresponding list of Posts:
var cat = _db.Categories.Where(a => a.Id == catId).FirstOrDefault();
if(cat != null)
ViewBag.Posts = cat.Posts;
return View();