I am trying to link my ASP.Net MVC (VS2013) to my SQL Server (SQL Server 2014 Mgt Studio) but failing! This is the code I have set up but i either get an 'System.Data.Entity.ModelConfiguration.ModelValidationException'on the ResultsView or the data from the table doesnt' show up. Any help would be much appreciated - I have attached my code below:
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GlobalMetricsTest2.Models
{
public class GMUSALong
{
public virtual int BID { get; set; }
public virtual string BMetrics { get; set; }
public virtual string BTopic { get; set; }
}
}
Context:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GlobalMetricsTest2.Models;
using System.Data.Entity;
namespace GlobalMetricsTest2.DAL
{
public class GMUSALongContext : DbContext
{
public DbSet<GMUSALong> GMTest { get; set; }
}
}
Controller:
using System.Web;
using System.Web.Mvc;
using GlobalMetricsTest2.DAL;
using GlobalMetricsTest2.Models;
namespace GlobalMetricsTest2.Controllers
{
public class GMUSALongController : Controller
{
private GMUSALongContext db = new GMUSALongContext();
public ActionResult Index()
{
var advItems = db.GMTest;
return View(advItems.ToList());
}
}
}
View:
#model IEnumerable<GlobalMetricsTest2.Models.GMUSALong>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<table>
<tr>
<th>ID</th>
<th>Metrics</th>
<th>Topic</th>
</tr>
#foreach (GlobalMetricsTest2.Models.GMUSALong item in Model)
{
<tr>
<td>#item.BID:</td>
<td>#Html.DisplayFor(modelItem => item.BMetrics)</td>
<td>#Html.DisplayFor(modelItem => item.BTopic)</td>
</tr>
}
</table>
From the beginner perspective, I would recommend you try another approach. Create your database table(s) as you desire. Then create a templated MVC project by navigating to New -> Project, select ASP.NET Web Application. You will be prompted with further options, select 'MVC'. This will give you a nice template example that you can reference for any MVC questions. Creating new project and adding MVC 5 with NUGET will start a cleaner example but requires more steps.
Now that you have your website created. Right click on your 'Models' folder, Add -> New Item, select ADO.NET Entity Data Model, you will be prompted with more options, select 'Code First from database, provide your database connection information, and select which objects you'd like imported. At this point you should have a functional data Context with all the required annotations assigned to non-standard naming conventions.
Now right-click on your 'Views' folder, Add -> 'New Scaffolded Item', select 'MVC 5 View', name your view (I'd recommend your model's name + 'View'), select which model you'd like to use, choose which type of screen you'd like to create, this would be 'List'. Once created you'll have a nice standard example of all the pieces you are trying to learn. Once you've gained the knowledge you need, you can make minor tweaks to this process to rapidly create highly functional screens for your site.
http://www.asp.net/visual-studio/overview/2013/aspnet-scaffolding-overview
Related
I use:
- MS SQL Server 2014 database;
- Entity Framework.
I am using GridControl with an "empty row" element.
The user is trying to add a new entry in the GridControl.
After adding a new record does not update the field, which is formed by the database.
In my case, this field is "ID".
It can also be other fields that the database forms.
The "ID" field is updated only after the new record is being edited.
Question.
How to make the field that is filled with the database updated in the GridControl after adding a new entry in the GridControl?
namespace Rsh.frm.frm3.Core.ModelEFFrm_3
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class PrbEntitiesF3 : DbContext
{
public PrbEntitiesF3()
: base("name=PrbEntitiesF3")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<tbl_930_3_2_Test> tbl_930_3_2_Test { get; set; }
}
}
namespace Rsh.frm.frm3.Core.ModelEFFrm_3
{
using System;
using System.Collections.Generic;
public partial class tbl_930_3_2_Test
{
public int Id { get; set; }
public string Text { get; set; }
}
}
public partial class Frm3UC : UserControl
{
PrbEntitiesF3 entiF3;
public Frm3UC()
{
InitializeComponent();
entiF3 = new PrbEntitiesF3();
}
public void FillGrid3()
{
entiF3.tbl_930_3_2_Test.Load();
bs3.DataSource = entiF3.tbl_930_3_2_Test.Local.ToBindingList();
gridControl3.DataSource = bs3;
}
public void Save()
{
entiF3.SaveChanges();
}
}
Update_1
I want to make the logic work:
1. User filled the field.
User. Clicked "Enter".
The code (or standard tools "devexpress") adds a new entry to the Grid.
The code (or standard tools "devexpress") saves an entry to the database.
The code (or standard tools "devexpress") fills in the fields that the database creates.
In my case, this is the "ID" field.
I want to say that the value of the "ID" field is created in the database.
This value needs to be displayed in the Grid for the new record that the user added.
The solution is to handle the GridView_FocusedRowChanged event.
Please see the following screencast:
https://screencast-o-matic.com/watch/cqnZFt0Qeb
I am new to asp.net core MVC framework(Before this I was using Laravel.)
I have a two table, Country and State, I will use InnerJoin to join those both table.
In my CountryModel, I have 4 property like below
public int CountryId { get; set; }
public string CountryName { get; set; }
public int StateId { get; set; }
public string StateList { get; set; }
SELECT c.CountryId,
c.CountryName,
s.StateId,
s.States AS 'StateName'
FROM _tbAddr_Country AS c
INNER JOIN _tbAddr_State AS s on s.CountryId = c.CountryId
The above is my sql query, in my Country Model property I have no "StateName" property but I have "StateList", I just want to map "StateList" to "StateName" by using DataAnnotation just like below, I have tried
[ColumnAttribute("StateName")]
public string StateList { get; set; }
And
[Column("StateName")]
public string StateList { get; set; }
These two is not working for me, I know I can solve this problem by simply change the "StateList" to "StateName", But I hope I can find alternative way like use "Column" or "ColumnAttribute" Data Annotation to solve this problem. Any help is appreciated.
P/S: I using .net core 1.1 and SQL Server Management Studio 2014
That's not working the way you think.
Column must match a table column name. You however have a projection using a join. So there is no table with such a name.
EntityFramework Core 1.x and 2.0 doesn't support ad-hoc mapping from Views or queries to an arbitrary model. This feature is currently on roadmap for 2.1 as "Read-only view types in the model".
Please note that this feature is located in the "stretch goal" section. It means, it's prioritized for 2.1, but changes are that not all of the goals will make it to 2.1 release and may be pushed to the next version if it's not done by the time 2.1 gets released (which should be around the time when ASP.NET Core 2.1 and/or .NET Core 2.1 releases)
If I had a simple model
public class Company
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
How would I convert this model into a SQL Server table with Entity Framework code-first?
Answer to your question would actually end up being a full tutorial.
That said, I suggest that you visit the following website and get yourself familiar with Entity Framework Code First concepts:
http://www.entityframeworktutorial.net/code-first/entity-framework-code-first.aspx
Mentioned tutorial has both conceptual overview as well as code samples.
Once you are done with tutorial, you will understand the following code snippet:
public class ApplicationContext : DbContext
{
public DbSet<Company> Companies { get; set; }
}
Then you need to create adequate migration and apply it to your database which will end up with creation of "Companies" or "Company" table (depending on EF version you are using).
I am trying to create a white list part for the site's settings that will allow an admin user to enter a list of urls that are considered "white listed". I'm having a problem with storing this information in the database though. When creating a new content type with information that belongs in the database you can use the following:
public class ShareBarSettingsPart : ContentPart<ShareBarSettingsPartRecord> {
public string AddThisAccount {
get { return Record.AddThisAccount; }
set { Record.AddThisAccount = value; }
}
}
to set the value of AddThisAccount in the database. My problem is I need a list of urls in the database and not just a single item. I tried the following but it gives me an error:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Records;
namespace Speedbump.Models
{
public class SpeedBumpSettingsRecord : ContentPartRecord
{
public virtual List<string> whiteList { get; set; }
}
public class SpeedBumpSettingsPart : ContentPart<SpeedBumpSettingsRecord>
{
public List<string> whiteList
{
get { return Record.whiteList; }
set { Record.whiteList.Add(value); } //I need to be able to add a single record to the list here
}
}
}
Any help would be greatly appreciated, thank you.
List<string> is not supported as a record property type. It doesn't matter however as you should never use a record for a site setting part. Use Store and Retrieve instead. Any existing settings part will give you an example.
Howdy, ya'll! First question on StackOverflow! :-)
So here's the scenario: We're working on a web app with Silverlight 4 and using WCF RIA Services 1.0 SP1 Beta for the web service. I have my entities in the Entity Framework Designer, but I'm using a slightly-modified ADO.NET C# POCO Entity Generator template to generate the classes.
What I'd like to do is have a method inside a Domain Service with the following signature:
[EnableClientAccess]
public class ResultService : DomainService
{
[Invoke]
public SerializableResult CalculateResult(EntityOne e1, EntityTwo e2);
}
I am returning both EntityOne and EntityTwo to the client through queries in other services, like so:
[EnableClientAccess]
public class EntityOneService : DomainService
{
public IQueryable<EntityOne> GetEntityOnes();
}
[EnableClientAccess]
public class EntityOneService : DomainService
{
public IQueryable<EntityTwo> GetEntityTwos();
}
Those classes are successfully being generated in the Silverlight project. The SerializableResult does not have a key.
When I try to compile, I get the following error: "Operation named 'CalculateResult' does not conform to the required signature. Parameter types must be an entity or complex type, a collection of complex types, or one of the predefined serializable types."
In my research, the most helpful information I found were in the comments of this post by Jeff Handley.
Of note, Peter asked in a comment:
I get an 'does not conform to the required signature ...' compile error if my complex object has an [Key] Attribute. When I remove this attribute I can use the object as parameter for an Invoke operation.
Jeff's response:
This is by design. Complex objects cannot have Key properties. If you have a Key the class gets treated as an Entity.
So it sounds as if any further efforts to try to get my method to work will be futile. However, I was wondering if anyone else has come across this problem, and what they did to solve it.
Thanks very much!
I have the following and it works for me.
namespace BusinessApplication2.Web
{
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
[EnableClientAccess()]
public class DomainService1 : DomainService
{
public IQueryable<EntityOne> GetEntityOnes()
{
return null;
}
public IQueryable<EntityTwo> GetEntityTwos()
{
return null;
}
[Invoke]
public SerializableResult GetSerializableResult(EntityOne one, EntityTwo two)
{
return new SerializableResult() { Result = "It woooooorrrked!" };
}
}
public class EntityOne
{
[Key]
public int Id { get; set; }
}
public class EntityTwo
{
[Key]
public int Id { get; set; }
}
public class SerializableResult
{
public string Result { get; set; }
}
}
Many thanks to Mr. Jeff Handley and Mr. Dinesh Kulkarni for the answer (through Twitter).
In order for an Entity to be used as a parameter in an invoke method, that Entity must be exposed through a query method existing within the same DomainService. The intention for this restriction is that
"Each domain service needs to be able to stand on its own."
By adding two dummy Query methods (see Jeff's answer for an example), I was able to compile my code.