How can I bind my MVC Model to a different table - c#

This seems like an easy question but I can't seem to find the answer.
I have a Model that looks like this ...
public class Application
{
public int Id { get; set; }
public string Title { get; set; }
public string LeadProgrammer { get; set; }
public string ConnectionStringCode { get; set; }
}
public class ApplicationDBContext : DbContext
{
public DbSet<Application> Applications { get; set; }
}
My actual table name is DBA_APPLICATIONS ... the model is, of course, just looking for dbo.Applications. How can I change this routing to the actual table?

Add this in your ApplcationDBContext class.
public class ApplicationDBContext : DbContext
{
public DbSet<Application> Applications { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Application>().ToTable("DBA_APPLICATIONS");
// otherwise EF assumes the table is called "Applications"
}
}

Related

Post a decimal value in database using ASP.NET Web API

I am working on an ASP.NET Web API project and I have a database that I am using, and the model that I am working on look something like this
public class PAY
{
public int ID { get; set; }
public string PAY_CODE { get; set; }
public Nullable<decimal> PAY_CASH { get; set; }
}
and I have a simple post method look like this:
[HttpPost]
public string AddPayROW(string PAY_CODE, decimal PAY_CASH,)
{
var PAY = new PAY()
{
PAY_CODE = PAY_CODE,
PAY_CASH = PAY_CASH,
};
db.PAY.Add(PAY);
db.SaveChanges();
return "Row added successfully";
}
My problem is kind of weird but when I post this decimal value to the table the last number is zero
For example, if I tried to post 1.999 will be saved like this 1.990
I am using SQL Server and the datatype is decimal(16, 3)
How can I fix this problem?
On your OnModelCreating function add this code,
modelBuilder.Entity<PAY>().Property(x => x.PAY_CASH).HasPrecision(18,3);
Hope it works.
Edit : Do you have DbContext like this? For example;
public partial class DBO : DbContext
{
public DBO()
: base("ConStrEtc")
{ }
public virtual DbSet<PAY> PAYs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PAY>().Property(x => x.PAY_CASH).HasPrecision(18, 3);
}
}
public class PAY
{
public int ID { get; set; }
public string PAY_CODE { get; set; }
public Nullable<decimal> PAY_CASH { get; set; }
}

Fluent API One-to–Zero-or-One becomes Many-to-One relationship in Database

I'm trying to create a One-to–Zero-or-One relationship between two tables in a Code First design with Fluent API. But when it gets created, the relationship in database has become a Many-to-One relationship. I have looked at several tutorials and many Questions on forums but I can't find the problem with my code.
Generated Database Scheme:
Scheme on Imgur
My DbContext file:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Eigendommen>().HasKey(e => e.Id);
modelBuilder.Entity<Gronden>().HasKey(g => g.Id);
modelBuilder.Entity<Eigendommen>()
.HasRequired(g => g.Grond)
.WithOptional(e => e.Eigendommen);
base.OnModelCreating(modelBuilder);
}
}
Base class of the table:
public abstract class EntityBase
{
public int Id { get; protected set; }
public EntityBase()
{
}
}
My Main table(One):
public class Eigendommen : EntityBase
{
public string Gemeente { get; set; }
public string Straat { get; set; }
public int Grond_Id { get; set; }
public virtual Gronden Grond { get; set; }
public Eigendommen() : base()
{
Gemeente = "Eksaarde";
Straat = "Ramstraat";
}
}
My second table(Zero-or-One):
public enum TypeGround { Bebouwd, Verkaveling };
public class Gronden : EntityBase
{
public double Opp { get; set; }
public TypeGround Type { get; set; }
public virtual Eigendommen Eigendommen { get; set; }
public Gronden() : base()
{
Opp = 11;
Type = TypeGround.Bebouwd;
}
}
I don't see a difference with the many tutorials I followed, I hope you can see the problem?
If you need more code, just ask!
Thank you in advance.

ASP.NET Core relation is in database but is not retrieved

I am new to ASP.NET Core and I am trying to setup basic relationship with EntityFramework Core. I have a NavigationCategory class that has 1:M relationship with WebPage class. The relationship is understood by my DB (It has a foreign key) but when retrieving the WebPage from repository, it has no NavigationCategory, even though it has NavigationCategoryId set.
public class WebPage : BaseEntity
{
private string _route;
public string Title { get; set; }
public string Body { get; set; }
[ForeignKey("NavigationCategory")]
public long NavigationCategoryId { get; set; }
public NavigationCategory NavigationCategory { get; set; }
public WebPage()
{
}
}
public class NavigationCategory : BaseEntity
{
public string Title { get; set; }
public IEnumerable<WebPage> WebPages { get; set; }
public NavigationCategory()
{
}
}
This is simple BaseEntity:
public class BaseEntity
{
public long Id { get; set; }
}
This is my DB context:
public class AppDataContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<KinderClass> KinderClasses { get; set; }
public DbSet<Feed> Feeds { get; set; }
public DbSet<NavigationCategory> NavigationCategories { get; set; }
public DbSet<WebPage> WebPages { get; set; }
public AppDataContext(DbContextOptions<AppDataContext> options) : base(options)
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<WebPage>()
.HasOne(wp => wp.NavigationCategory)
.WithMany(c => c.WebPages)
.HasForeignKey(wp => wp.NavigationCategoryId);
}
}
You need to explicitly include any navigation property you want included when you fetch entities using EF Core. For example, update your query as follows:
var webpage = dbContext.WebPages
.Include(w => w.NavigationCategory)
.FirstOrDefault();
Note, you need these two namespaces, at minimum:
using Microsoft.EntityFrameworkCore;
using System.Linq;
Learn more about loading related data and why lazy loading shouldn't be used in web apps.

C# Entity Framework Code First Abstract Inheritance

In the following classes I am trying to do a code first setup using abstract base classes. Sorry if this is a duplicate question. I did try to search the site and google for an answer but nothing I have tried has worked.
public abstract class IDObject
{
[Key]
public Int32 ID { get; internal set; }
}
public abstract class NamedObject : IDObject
{
public String Name { get; set; }
}
public abstract class HWObject : NamedObject
{
public Double Free { get; set; }
public Double Max { get; set; }
public Double Used { get; set; }
}
public abstract class CPUObject : HWObject { }
public abstract class MemoryObject : HWObject { }
public abstract class StorageObject : HWObject { }
public class Server : NamedObject
{
[JsonConstructor]
internal Server() { }
public String CompanyName { get; set; }
public Boolean IsRunning { get; set; }
public CPUObject CPU { get; set; }
public MemoryObject Memory { get; set; }
public StorageObject Storage { get; set; }
}
I have the following DBContext:
public class DataContext : DbContext
{
public DataContext() : base("name=DataContext") { }
public DbSet<Server> Servers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
When I try to view the Read-Only Data Model I get the following error:
System.InvalidOperationException: The abstract type 'MyApp.CPUObject' has no mapped descendants and so cannot be mapped. Either remove 'MyApp.CPUObject' from the model or add one or more types deriving from 'MyApp.CPUObject' to the model.
How do I change the DBContext so the error goes away?
EDIT:
According to the answer below I have removed abstract from the CPUObject, MemoryObject and StorageObject as they should have never been abstract.
I have changed the DBContext to the following: (The mappings create a 1 to 1 relationship)
public class DataContext : DbContext
{
public DataContext() : base("name=DataContext") { }
public DbSet<Server> Servers { get; set; }
public DbSet<CPUObject> CPUObjects { get; set; }
public DbSet<MemoryObject> MemoryObjects { get; set; }
public DbSet<StorageObject> StorageObjects { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Server>().HasRequired(u => u.CPU).WithRequiredDependent().Map(m => m.MapKey("CPUID"));
modelBuilder.Entity<Server>().HasRequired(u => u.Memory).WithRequiredDependent().Map(m => m.MapKey("MemoryID"));
modelBuilder.Entity<Server>().HasRequired(u => u.Storage).WithRequiredDependent().Map(m => m.MapKey("StorageID"));
}
}
CPUObject is currently an abstract class, which cannot be instantiated. Just remove the abstract to make it a concrete object. Then, add public DbSet<CPUObject> CPUs { get; set; } to your DBContext
You are currently getting the error because EF is looking for a concrete class, so the error says you can make another concrete class that inherits (i.e. 'deriving from') CPUObject

The operation failed because an index or statistics with name 'IX_AuctionId' already exists on table 'Bids'

This question is related to this question which was never answered. I have a more real world example here though - so hoping for some help.
I have an auction, bid and auctiondetail(a flattened table) class.
I am trying to include my bids in the auction as well as auctiondetail table, auction and auctiondetail have the same PK
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
namespace OnCall.VirtualWarehouse.Data.Models.Auctions
{
using System;
public class AuctionCopy
{
public Guid AuctionCopyId { get; set; }
public virtual Collection<BidCopy> BidCopies { get; set; }
}
public class BidCopy
{
public Guid BidCopyId { get; set; }
public Guid AuctionCopyId { get; set; }
public AuctionCopy AuctionCopy { get; set; }
}
public class AuctionDetailCopy
{
[Key]
public Guid AuctionCopyId { get; set; }
public virtual Collection<BidCopy> BidCopies { get; set; }
}
}
Here's my DBContext:
public class DataContext : DbContext
{
static DataContext()
{
Database.SetInitializer(new DropCreateIfChangeInitializer());
}
public DataContext()
{
Configuration.ProxyCreationEnabled = false;
}
public IDbSet<AuctionCopy> AuctionCopy { get; set; }
public IDbSet<BidCopy> BidCopy { get; set; }
public IDbSet<AuctionDetailCopy> AuctionDetailCopy { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
public void Seed(DataContext context)
{
}
}
When generating the database, I get
The operation failed because an index or statistics with name 'IX_AuctionId' already exists on table 'Bids'.
Any ideas how I can get this to work?
The bug come from EF4.3 (and 4.3.1).
It should be fixed for the next release.
Have a look on Unhandled Exception after Upgrading to Entity Framework 4.3.1. They purpose a workaround using migration system.

Categories