Create data without Entity Framework - c#

I'm trying to insert data into my database using ASP.NET MVC without Entity Framework and it doesn't work.
I tried these tutorials:
InsertUpdateDelete in ASP.NET MVC 5 without Entity Framework | C# Tutorial
ASP.Net MVC CRUD Operation without Entity Framework - YouTube
This is my controller:
public class AdresaController : Controller
{
private OracleConnection conn;
public AdresaController()
{
Connection connection = new Connection();
conn = connection.GetOracleConnection();
}
public ActionResult Create()
{
return View();
}
// POST: Adresa/Create
[HttpPost]
public ActionResult Create(AdresaModel obAdresa)
{
try
{
AdresaRepository x = new AdresaRepository(conn);
string result = x.CreateAdr(obAdresa);
ViewData["result"] = result;
ModelState.Clear();
return View();
}
catch
{
return View();
}
}
}
This is my repository:
public class AdresaRepository
{
private OracleConnection oracleConnection;
public AdresaRepository(OracleConnection oracleConnection)
{
this.oracleConnection = oracleConnection;
}
public string CreateAdr(AdresaModel obAdresa)//
{
string result = "";
try
{
string oString = "insert into adresa(id_adresa, strada, nr_str, bloc, localitate_id_loc) values(#id_adresa, #strada, #nr_str, #bloc, #localitate_id_loc)";
var cmdc = new OracleCommand(oString, oracleConnection);
cmdc.CommandType = CommandType.StoredProcedure;
cmdc.Parameters.Add(new OracleParameter("#id_adresa", obAdresa.IdAdresa));
cmdc.Parameters.Add(new OracleParameter("#strada", obAdresa.Strada));
cmdc.Parameters.Add(new OracleParameter("#nr_str", obAdresa.NrStrada));
cmdc.Parameters.Add(new OracleParameter("#bloc", obAdresa.Bloc));
cmdc.Parameters.Add(new OracleParameter("#localitate_id_loc", obAdresa.IdLoc));
oracleConnection.Open();
result = cmdc.ExecuteNonQuery().ToString();
oracleConnection.Close();
return result;
}
catch
{
return result = "";
}
finally
{
oracleConnection.Close();
}
}
}
And here is my model:
public class AdresaModel
{
public int IdAdresa { get; set; }
public string Strada { get; set; }
public string NrStrada { get; set; }
public string Bloc { get; set; }
public int IdLoc { get; set; }
}

#kashi_rock is on the right track but didn't explain the issue very well. When you execute a command, you can either set the CommandType to StoredProcedure and the CommandText to the name of a stored procedure or you can set CommnadType to Text (which is the default) and the CommandText to a SQL statement. You are mixing and matching. You are providing inline SQL but saying that you want to use a stored procedure. Basically, get rid of this line:
cmdc.CommandType = CommandType.StoredProcedure;
I find it very difficult to believe that no exception was thrown. It should have tried to tell you that there was no stored procedure with the name you specified or the like. You need to up your exception handling game or you'll be mystified by other things that seem to just not work with no indication of why.

Related

C# How to return list of DapperRow to List of strongly types objects?

I have a generic method that takes in any class or a list of any class and will return a list of rows or a single row from the database.
The problem I am having is turning the list of dapper rows into a list of strongly typed objects. Can someone help here?
This is the dapper method
public async Task<dynamic> ExecuteQueryAsync<T>(string sqlStatement)
{
using (var connection = new SqlConnection(_connectionString))
{
await connection.OpenAsync();
var retVal = await connection.QueryAsync<T>(sqlStatement);
return retVal;
}
}
I can call this method either like this passing a list of models as I want to return this back to me.
var sqlStatement = $#"Select * from ClientReferral";
var retVal= await _dapperHelper.ExecuteQueryAsync<List<ReferralModel>>(sqlStatement);
return retVal.ToList(); <---- Errors here
or like this as a single query
var sqlStatement = $#"Select * from ClientReferral where id = 1";
var retVal= await _dapperHelper.ExecuteQueryAsync<ReferralModel>(sqlStatement);
In any case I need to convert the list of DapperRows into a list of my model
var retVal = await connection.QueryAsync<T>(sqlStatement);
public class ReferralModel
{
public string? ClientName { get; set; }
public int ClientId { get; set; }
public string? ClientNumber { get; set; }
public string? ClientDOB { get; set; }
public DateTime? DateSubmitted { get; set; } = default;
public string? ReportStatus { get; set; }
}
You should change you code from dynamic to IEnumerable<T> or List<T> then it will work
public async Task<IEnumerable<T>> ExecuteQueryAsync<T>(string sqlStatement)
{
using (var connection = new SqlConnection(_connectionString))
{
await connection.OpenAsync();
var retVal = await connection.QueryAsync<T>(sqlStatement);
return retVal;
}
}

Controller.Json() returns null

I'm only using ASP.Net and MVC, no other libraries.
The code is the following:
//ExpensesController.cs - the controller
public IActionResult getExpenses()
{
List<ExpensesViewModel> list = new List<ExpensesViewModel>();
string connectionString = "Data Source=DESKTOP-72RT825;Initial Catalog=AccountingDB;Integrated Security=True;Pooling=False";
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
SqlCommand query = new SqlCommand("Select * from Expenses", sqlConnection);
try
{
SqlDataReader reader;
reader = query.ExecuteReader();
while (reader.Read())
{
String name = reader.GetValue(0).ToString();
String value = reader.GetValue(1).ToString();
String date = reader.GetValue(2).ToString();
list.Add(new ExpensesViewModel() { Name = name, Date=date, Value = value });
Debug.Print(name + " " + " " + value);
}
}
catch (SqlException ex)
{
Debug.Print(ex.Message);
return Json(ex.Message);
}
JsonResult jsonResult = null;
try
{
jsonResult = Json(list);
}
catch(Exception ex)
{
Debug.Write(ex.Message);
}
return jsonResult;
}
//The View Model
public class ExpensesViewModel
{
public string Name;
public string Value;
public string Date;
}
The data that Json(list) returns is null, even though the list is not, I looked in the debugger, the connection to the DB is good, the data arrives, it is put into the list, but when I try and convert it to Json it fails. I've tried adding elements into the list manually, the Json function still returns null.
Change your view model to use properties, not fields:
public class ExpensesViewModel
{
public string Name { get; set; }
public string Value { get; set; }
public string Date { get; set; }
}
The reason is that the default model binder binds to properties with public getters/setters.

Is there a way to easly bind a grid to a table in Xamarin, like in my WinForms code?

i am new to xamarin, i need to easily link a grid (or something similar) to my MySql database table.
In WinForms I had done it by putting a grid with the designer and with a few lines of code, but instead with Xamarin I can't do anything ...
My current project is a XamarinForm with the default "tab" preset.
Here is the WinForm code:
try
{
MySqlConnection cnn;
string connetionString = "server=sql7.freesqldatabase.com;database=------;port=----;uid=-------;pwd=------;";
cnn = new MySqlConnection(connetionString);
DataTable dt = new DataTable();
MySqlCommand cmd;
cnn.Open();
cmd = cnn.CreateCommand();
cmd.CommandText = "SELECT * from Products";
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dt);
dataGridView1.DataSource = dt; //dataGridView WinFrom component
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Is there a way to do this in Xamarin?
(my goal is to display all the db table in one page)
Welcome to SO!
Although there is not the same way that Xamarin can use DataTable as Source directly, but there is an another way to convert Table Date and make it used for Control(Such as CollectionView, DataGrid, etc).
For example, ItemSource can be set as follows:
MyDataGrid.ItemsSource = await TodoItemDatabase.Database.Table<TodoItem>().ToListAsync();
Here the TodoItem is the Model of table data, you need to create it in Xamarin Forms manually. Then the app will convert the table data to list data according to the model style.
using SQLite;
public class TodoItem
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
public bool Done { get; set; }
}
About using Databases in Xamarin, you can refer to this official document.And there is a sample project for reference. Above code TodoItemDatabase class also based on this sample.
Here is the TodoItemDatabase class:
public class TodoItemDatabase
{
static readonly Lazy<SQLiteAsyncConnection> lazyInitializer = new Lazy<SQLiteAsyncConnection>(() =>
{
return new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
});
public static SQLiteAsyncConnection Database => lazyInitializer.Value;
static bool initialized = false;
public TodoItemDatabase()
{
InitializeAsync().SafeFireAndForget(false);
}
async Task InitializeAsync()
{
if (!initialized)
{
if (!Database.TableMappings.Any(m => m.MappedType.Name == typeof(TodoItem).Name))
{
await Database.CreateTablesAsync(CreateFlags.None, typeof(TodoItem)).ConfigureAwait(false);
}
initialized = true;
}
}
public Task<List<TodoItem>> GetItemsAsync()
{
return Database.Table<TodoItem>().ToListAsync();
}
public Task<List<TodoItem>> GetItemsNotDoneAsync()
{
return Database.QueryAsync<TodoItem>("SELECT * FROM [TodoItem] WHERE [Done] = 0");
}
public Task<TodoItem> GetItemAsync(int id)
{
return Database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
}
public Task<int> SaveItemAsync(TodoItem item)
{
if (item.ID != 0)
{
return Database.UpdateAsync(item);
}
else
{
return Database.InsertAsync(item);
}
}
public Task<int> DeleteItemAsync(TodoItem item)
{
return Database.DeleteAsync(item);
}
}
And Constants class which contains database name and other things.
public static class Constants
{
public const string DatabaseFilename = "TodoSQLite.db3";
public const SQLite.SQLiteOpenFlags Flags =
// open the database in read/write mode
SQLite.SQLiteOpenFlags.ReadWrite |
// create the database if it doesn't exist
SQLite.SQLiteOpenFlags.Create |
// enable multi-threaded database access
SQLite.SQLiteOpenFlags.SharedCache;
public static string DatabasePath
{
get
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(basePath, DatabaseFilename);
}
}
}

Import the values stored in the database from the controller

[HttpGet]
public ActionResult Create()
{
Articles article = new Articles();
return View(article);
}
[HttpPost]
public ActionResult Create(Articles article)
{
try
{
article.Family = article.ArticleIDX; //그룹번호
article.Parent = 0; //순서
article.Depth = 1; //그룹내 최상위 글로부터 매겨지는 순서
article.Indent = 0; //들여쓰기
article.ModifyDate = DateTime.Now;
article.ModifyMemberID = User.Identity.Name;
db.Articles.Add(article);
db.SaveChanges();
if (Request.Files.Count > 0)
{
var attachFile = Request.Files[0];
if (attachFile != null && attachFile.ContentLength > 0)
{
var fileName = Path.GetFileName(attachFile.FileName);
var path = Path.Combine(Server.MapPath("~/Upload/"), fileName);
attachFile.SaveAs(path);
ArticleFiles file = new ArticleFiles();
file.ArticleIDX = article.ArticleIDX;
file.FilePath = "/Upload/";
file.FileName = fileName;
file.FileFormat = Path.GetExtension(attachFile.FileName);
file.FileSize = attachFile.ContentLength;
file.UploadDate = DateTime.Now;
db.ArticleFiles.Add(file);
db.SaveChanges();
}
}
ViewBag.Result = "OK";
}
catch (Exception ex)
{
Debug.WriteLine("Board");
Debug.WriteLine(ex.ToString());
ViewBag.Result = "FAIL";
}
return View(article);
//return RedirectToAction("ArticleList");
}
[HttpGet]
public ActionResult ReplyCreate(int aidx)
{
Articles articleReply = new Articles();
return View(articleReply);
}
[HttpPost]
public ActionResult ReplyCreate(Articles replyArticles)
{
Articles articles = new Articles();
try
{
//부모글 불러오기(글번호로 불러오기)
Articles note = db.Articles.Find(articles.ArticleIDX);
//Family는 원글의 번호
replyArticles.Family = replyArticles.ArticleIDX;
//Parent 순서
//Depth 는 답글의 글 번호
//Indent 들여쓰기
replyArticles.ModifyDate = DateTime.Now;
replyArticles.ModifyMemberID = User.Identity.Name;
db.Articles.Add(replyArticles);
db.SaveChanges();
ViewBag.Result = "OK";
}
catch (Exception ex)
{
ViewBag.Result = "FAIL";
}
return View(replyArticles);
}
public partial class Articles
{
[Key]
public int ArticleIDX { get; set; }
public int? Family { get; set; }
public int? Depth { get; set; }
public int? Indent { get; set; }
public int? Parent { get; set; }
[StringLength(200)]
public string Title { get; set; }
[Column(TypeName = "text")]
public string Contents { get; set; }
[StringLength(50)]
public string Category { get; set; }
[StringLength(20)]
public string ModifyMemberID { get; set; }
public DateTime? ModifyDate { get; set; }
public virtual Members Members { get; set; }
}
The above code is the code I implemented.
Articles created using the create method are stored in the database.
What do you do when you try to recall a post stored in the database with ReplyCreate?
The null value is often entered into the model.
I try to find it using the primary key, but the primary key also has a null value.
Articles note = db.Articles.Find(articles.ArticleIDX);
does not work because articles is an empty object, due to the line
Articles articles = new Articles();
just above. You never set any of the fields in this object, including the ArticleIDX, before calling the Find method.
I think you probably intended to search using the value passed in to the controller? In that case it would need to be
Articles note = db.Articles.Find(replyArticles.ArticleIDX);
because replyArticles is the variable which was received from the browser in the request. I assume this contains a value in the ArticleIDX field.
Having said that, I don't know what the purpose of this line of code is, because you never use the note object in any of the following code, so I don't know why you needed to find it.

Three-tier architecture implementation in Windows form application

I am trying to insert data into a database using a three-tier architecture, but I am stuck and I cannot proceed further.
This is my code
First is UI part:
public void assignField()
{
string maritalCondition = "";
string sex = "";
assignObj.Registered_Date = dateTimePicker1_Date.Value;
assignObj.First_Name = txt_FirstName.Text;
if (comboBox2_MaritalStatus.SelectedIndex == 0)
{
maritalCondition = "Single";
}
else
maritalCondition = "Married";
assignObj.Marital_Status = maritalCondition;
if (RadioButton_Male.Checked == true)
sex = "Male";
else
sex = "Female";
assignObj.Gender = sex;
this.txt_Age.Text = Convert.ToInt32(age).ToString();
}
private void btnRegister_Click(object sender, EventArgs e)
{
assignField();
}
Next is the middle tier:
public class CustomerDataType
{
private DateTime registered_Date;
private string first_Name;
private int age;
private string marital_Status;
private string gender;
public DateTime Registered_Date
{
get { return registered_Date; }
set { registered_Date = value; }
}
public string First_Name
{
get { return first_Name; }
set { first_Name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Marital_Status
{
get { return marital_Status; }
set { marital_Status = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public void insertInfo()
{
CustomerDataAccess insertObj = new CustomerDataAccess(Registered_Date, First_Name, Age, Marital_Status, Gender);
insertObj.insertCustomerInfo();
}
}
and last is the data access tier:
public class CustomerDataAccess
{
public CustomerDataAccess(DateTime Registered_Date, string First_Name, int Age, string Marital_Status, string Gender)
{
this.registrationDate = Registered_Date;
this.fName = First_Name;
this.userAge = Age;
this.marriageStatus = Marital_Status;
this.userGender = Gender;
}
SqlConnection con;
SqlCommand cmd;
DateTime registrationDate;
string fName = "";
int userAge;
string marriageStatus;
string userGender;
public void insertCustomerInfo()
{
try
{
con = new SqlConnection("Data Source=LAKHE-PC;Initial Catalog=Sahakari;Integrated Security=True");
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "sp_registerCust";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Registered_Date", SqlDbType.DateTime);
cmd.Parameters["#Registered_Date"].Value = registrationDate;
cmd.Parameters.Add("#First_Name", SqlDbType.VarChar);
cmd.Parameters["#First_Name"].Value = fName;
cmd.Parameters.Add("#Age", SqlDbType.Int.ToString());
cmd.Parameters["#Age"].Value = userAge;
cmd.Parameters.Add("#Marital_Status", SqlDbType.VarChar);
cmd.Parameters["#Marital_Status"].Value = marriageStatus;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar);
cmd.Parameters["#Gender"].Value = userGender;
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here with the stored procedure, there is no problem and and from SQL Server I can insert data into table easily. But from windows form, it does not insert data in table. Plz help me.
I'll do something like below
UI
CustomerHandler custHandler = new CustomerHandler();
// create Customer object and pass to insert method
if (custHandler.InsertCustomer(new Customer(){
FirstName = txt_FirstName.Text, Registered_Date =dateTimePicker1_Date.Value,
//decalare other parameters....
))
{
// insert Success, show message or update label with succcess message
}
In my BL
public class CustomerHandler
{
// in BL you may have to call several DAL methods to perform one Task
// here i have added validation and insert
// in case of validation fail method return false
public bool InsertCustomer(Customer customer)
{
if (CustomerDataAccess.Validate(customer))
{
CustomerDataAccess.insertCustomer(customer);
return true;
}
return false;
}
}
In MY DAL
// this is the class you going to use to transfer data across the layers
public class Customer
{
public DateTime Registered_Date { get; set; }
public string FirstName { get; set; }
//so on...
}
public class CustomerDataAccess
{
public static void insertCustomer(Customer customer)
{
using (var con = new SqlConnection("Data Source=LAKHE-PC;Initial Catalog=Sahakari;Integrated Security=True"))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "sp_registerCust";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Registered_Date", customer.Registered_Date);
cmd.Parameters.AddWithValue("#FirstName", customer.FirstName);
// so on...
cmd.ExecuteNonQuery();
}
}
internal static bool Validate(Customer customer)
{
// some validations before insert
}
}
Your middle tier consists of classes holding the values you require in properties. Instead of writing the data access manually, try using the Entity Framework (EF) which does that for you.
Here (at MSDN) you can find a quickstart example which shows you how you can use it.
Instead of mapping the fields manually and executing a query, the Entity Framework does that which means you just have to assign the values to the object's properties and call SaveChanges() - the SQL code is created and executed automatically by the EF.
For further reading, there is also a lot to find here (at Stackoverflow).

Categories