Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a project coming up so I decided to look at the entity framework. If I don't have to create a data manager I think this would be the way to go, if it works. I see lots of things about it but none of them are clear.
It created this class
namespace EFTest
{
using System;
using System.Collections.Generic;
public partial class SalesRepresentative
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
}
}
How do I use it? Looking for examples I see things like this:
using (var ctx = new Context())
{
Employee emp = new Employee() { name = "Prashant" };
ctx.Employees.Add(emp);
ctx.SaveChanges();
}
I have a file called Model.Comntext with no context class in it. I tried changing it to dBContext but that doesn't work either.
I also found this:
CustomersComponent custc = new CustomersComponent();
Customers cust = custc.getCustomer(Id);
txtName.Text = cust.Name;
ddlCategories.SelectedValue = cust.Category.Id.ToString();
Well that has a Customer and a CustomerComponent. I have no such Component classes. I've spent half a day looking into this and am starting to wonder if the Entity Framework is a cousin of Microsoft Bob. Unless someone can tell me what I'm missing I will have to write my own data manager.
I resume step by step:
1 - Create a console project.
2 - Install EF using Nuget: Install-Package EntityFramework
3 - Create SalesRepresentative:
namespace EF {
public partial class SalesRepresentative {
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
}
}
4 - Create GeneralContext
namespace EF {
public class GeneralContext: DbContext {
public DbSet<SalesRepresentative> SalesRepresentatives { get; set; }
}
}
5 - So:
namespace EF {
class Program {
static void Main(string[] args) {
using (var ctx = new GeneralContext()) {
SalesRepresentative emp = new SalesRepresentative() { Name = "Prashant" };
ctx.SalesRepresentatives.Add(emp);
ctx.SaveChanges();
}
}
}
}
Note: In the App.config file (or web.config) you should customize the connection string.
Related
This is a C# Question, using .NET framework built on Asp.NET Boilerplate.
Again, to re-emphasis the question being asked is "HOW...", so if an answer that was provided was a url link or a descriptive explanation on how something was supposed to be done, i would very much appreciate it. (Dont answer questions on how to tie shoelace by showing a picture of a tied shoe, nor do you answer "how to fish" by showing a recording of someone fishing...)
Since the question is pretty basic (i don't need to rephrase/repeat the header again), i'll give an example.
If i have a Forum service, and i create a class to load a Thread. Inside that thread class should be some sort of collection, array, list, or even a dbset of Post that is pulled on construct.
[Table("Thread", Schema = "dbo")]
public class ThreadModel
{
[Key]
public long Id { get; set; }
public string Title { get; set; }
//Idea 1
//Value should automatically be pulled and cached the moment class connects to database
public Post[] Posts { get; set; }
//Idea 2
//Post has a constructor to return all post that matches a thread id. While new tag keeps the return value constantly refreshed.
public Post[] Posts { get { return new Post(this.Id) } }
//Idea 3
//Not sure how collection is supposed to work. Does it automatically just pull or will i need to make a method to request?
public virtual ICollection<Post> Posts { get; set; }
//Example constructor
//When connected to database key-value pairs that match database labels will automatically get stored in class
protected ThreadModel()
{
//Idea 1-A
//Should be a value of null or empty if database yields no results
Posts = new Post();
}
public ThreadModel(int threadid) : this()
{
//Idea 1-A
Id = threadid;
//new Post => returns all posts in db
//Posts default value is all post in db
Posts = Posts.Select(post => post.threadid == this.id)
//Idea 3-A
Posts = Posts.Get(post => post.threadid == this.id)
//Idea 4
Posts = new Posts().GetThread(threadid);
}
}
Side questions
If all entities are created by inheriting Entity then at what point am i exposed to EntityFramework and DbContext?
I love this example here, submitted by a user as they attempt to connect ABP to their database. But their example doesn't show parent/child resources. I'm unable to find the guide they used to create that, and how it relates back to using ABP to fetch EntityFramework's DbContext example
How does this work? I'm unable to find instructions or explanation for this? (What am i to enter into google to get answers on these mechanics?)
[Table("AbpItems")]
public class Item : Entity
{
[ForeignKey("PostId")]
public Post Post { get; set; }
public int PostId { get; set; }
}
How does this integrate into/with abp's EntityFramework?
Where am i supposed to be creating my Database Table/Class? The project follows the Core.csproj, Application.csproj, and EntityFramework.csproj assembly layout. But it seems like every example is creating the classes at different stages or locations of the solution.
use GetAllIncluding. See https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2617
Here's a complete solution ;
namespace EbicogluSoftware.Forum.Threads
{
[Table("Threads")]
public class Thread : FullAuditedEntity
{
[Required]
[StringLength(500)]
public virtual string Title { get; set; }
[Required]
[StringLength(2000)]
public virtual string Text { get; set; }
public virtual List<Post> Posts { get; set; }
public Thread()
{
Posts = new List<Post>();
}
}
[Table("Posts")]
public class Post : FullAuditedEntity
{
[Required]
[StringLength(2000)]
public virtual string Text { get; set; }
}
public class ThreadDto
{
public string Title { get; set; }
public string Text { get; set; }
public List<PostDto> Posts { get; set; }
public ThreadDto()
{
Posts = new List<PostDto>();
}
}
public class PostDto
{
public string Text { get; set; }
}
public class ThreadAppService : IApplicationService
{
private readonly IRepository<Thread> _threadRepository;
public ThreadAppService(IRepository<Thread> threadRepository)
{
_threadRepository = threadRepository;
}
public async Task<List<TenantListDto>> GetThreads()
{
var threads = await _threadRepository.GetAllIncluding(x => x.Posts).ToListAsync();
return threads.MapTo<List<TenantListDto>>();
}
}
}
Where am i supposed to be creating my Database Table/Class?
You can create them in YourProject.Core.proj
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I do not understand why complex types do not allow to refrence entity types. I mean they do, but all properties of the refrenced entity type are then stored in the same table as the class including the complex types.
I do not see any reason for this and it is a great limitation.
It seems Entity Framework cannot distinguish between the referenced entities. For example, it is unable to automatically assign keys to them:
The database in the previous image was created using the following code:
static void CreateAndSeedDatabase()
{
Context context = new Context();
ReferencedClass anotherClass1 = new ReferencedClass(){Name="instance1"};
ReferencedClass anotherClass2 = new ReferencedClass() { Name = "instance2" };
ComplexTypeClass complexType1 = new ComplexTypeClass(){ReferencedClassProp = anotherClass1};
ComplexTypeClass complexType2 = new ComplexTypeClass() { ReferencedClassProp = anotherClass2 };
Parent parent1 = new Parent() { ComplexTypeClassProp = complexType1 };
Parent parent2 = new Parent() { ComplexTypeClassProp = complexType2 };
context.Parents.Add(parent1);
context.Parents.Add(parent2);
context.SaveChanges();
}
public class Context : DbContext
{
public Context()
{
Database.SetInitializer<Context>(new DropCreateDatabaseAlways<Context>());
Database.Initialize(true);
}
public DbSet<Parent> Parents { get; set; }
}
public class Parent
{
public int Id { get; set; }
public ComplexTypeClass ComplexTypeClassProp { get; set; }
}
[ComplexType]
public class ComplexTypeClass
{
public ReferencedClass ReferencedClassProp { get; set; }
}
public class ReferencedClass
{
public int Id { get; set; }
public string Name { get; set; }
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
In my model Account I have a property like this
public List<String> Roles { get; set; }
Later on I want to get that property but convert it IList<IApplicationUserRole<Role>>, so I have this function
public IList<IApplicationUserRole<Role>> Roles
{
get
{
return _account.Roles; // how do I convert this in the specific type intended.
}
}
Here is my IApplicationUserRole
public interface IApplicationUserRole<TRoleModel> : IRole<string>
where TRoleModel : EntityModel
{
TRoleModel Role { get; set; }
String Name { get; set; }
}
I am a newbie to this thing. Looking forward for any help.
Say you have your implementing class be something like:
public class ApplicationUserRole : IApplicationUserRole<T> where T : Role
{
public ApplicationUserRole()
{
}
public User User { get; set; }
public T Role { get; set; }
}
Then, you'd do something like this:
public IList<IApplicationUserRole<Role>> Roles
{
get
{
return _account.Roles
.Select(r => new ApplicationUserRole { Role = roleService.FindRoleByName(r) })
.Cast<IApplicationUserRole<Role>>()
.ToList();
}
}
Where roleService is some way of building a Role instance from the role name (which above is r)
NOTE: This being said, there is a catch in the above implementation. Since Roles is a property it should not do data access operations. So, in this case, you should create a method instead of a property.
I would start with something like this:
public IList<IApplicationUserRole<Role>> Roles
{
get
{
return _account.Roles.Select(r=>
new ApplicationUserRole<Role>() {Name = r})
.Cast<IApplicationUserRole<Role>>()
.ToList();
}
}
This assuming that you have a class that implements the IApplicationUserRole<Role> interface.
As #MartinLiversage says you can't directly convert List<T> to List<U>, you have to manually do the conversion.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I copied this code from this article and I don't get any idea why define class inside classes as properties. Also, what happens when the class PersonalLoan is instantiated ?
public class PersonalLoan
{
public string AccountNumber { get; set; }
public string AccounHolderName { get; set; }
public Loan LoanDetail { get; set; }
public PersonalLoan(string accountNumber)
{
this.AccountNumber = accountNumber;
this.AccounHolderName = "Sourav";
this.LoanDetail = new Loan(this.AccountNumber);
}
}
public class Loan
{
public string AccountNumber { get; set; }
public float LoanAmount { get; set; }
public bool IsLoanApproved { get; set; }
public Loan(string accountNumber)
{
Console.WriteLine("Loan loading started");
this.AccountNumber = accountNumber;
this.LoanAmount = 1000;
this.IsLoanApproved = true;
Console.WriteLine("Loan loading started");
}
}
I suspect that this code snippet is an example of what you should avoid: LoanDetail property of type Loan inside a class PersonalLoan suggests a has-a relationship between the classes. In other words, the authors of this code snippet are trying to say that
Personal loan has a Loan
This, however, is unlikely the relationship that they are trying to model: in reality,
Personal loan is a Loan
The relationship is-a is modeled using inheritance, not composition. In other words, they should have written this:
public class PersonalLoan : Loan {
public PersonalLoan(string accountNumber) : base(accountNumber) {
...
}
...
}
Another issue that points to the model being incorrect is that both PersonalLoan and the Loan inside it have the same accountNumber, which is stored in two places within the same object. When you see this, you know something is not right. The reason you get two account numbers is that when PersonalLoan gets instantiated, its constructor also instantiates Loan, passing it the same accountNumber.
This is not to say that embedding objects inside other objects is wrong. For example, if you were to model a borrower address as a class, you would end up with something like this:
class Address {
public string Country {get;set;}
public string City {get;set;}
... // And so on
}
class Borrower {
public Address MailingAddress {get;set;}
... //
}
This model is perfectly valid, because Borrower has an Address.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I receive from client a raw string as this:
{ "\"wrapper\": {\"system\": { \"session\":\"ed6d1cc6-82f9-46e8-91bb-eae341a771cf\", \"ip\":\"\", \"station\":\"\"},{ \"personal_profile\": {\"suffix\":\"1096\",\"first_name\":\"Varvara\",\"middle_name\":\"\",\"last_name\":\"Terlouw\",\"street\":\"\",\"number\":\"\",\"add\":\"\",\"postal\":\"\",\"city\":\"\",\"state\":\"\",\"country\":\"\",\"birthday\":\"\",\"relation_type_id\":\"\"}},{ \"personal_contacts\": {\"contact_type_id_0\":\"409\",\"contact_0\":\"06-26096994\",\"contact_0\":\"on\"},{\"contact_type_id_0\":\"420\",\"contact_0\":\"jj#vv.com\",\"contact_0\":\"on\"},{\"contact_type_id_0\":\"\",\"contact_0\":\"\",\"contact_0\":\"on\"}},{ \"personal_work\": {}},{\"personal_connected\": {}},{\"personal_interests\": {}}}} "
I get the string in into my webservice and need to convert this to LIST<> so I can process the data to my database, preferable with my classes
here and old example of a class i used a while ago as another example for simple json serialize :
internal class CFingerPrint
{
public string WanIP;
public string MacAddress;
public string getClassEncrypted()
{
return new JavaScriptSerializer().Serialize(this);
}
public CFingerPrint getClassDecrypted(string sSerializedClass)
{
return new JavaScriptSerializer().Deserialize<CFingerPrint>(sSerializedClass);
}
}
I use the same way to communicate with other languages a lot and haven't had any issue yet except Dates that are problematic in JSON but that's another story.
Edit : example how to use :
// create new class
var originalClass = new CFingerPrint();
// fill some data
originalClass.WanIP = "test1";
originalClass.MacAddress= "test2";
// serialize to json string
var classSerialized = originalClass.getClassEncrypted();
// create new class from string only
var newClass = new CFingerPrint().getClassDecrypted(classSerialized);
Console.WriteLine(newClass.WanIP); // output "test1"
Console.WriteLine(newClass.MacAddress); // output "test2"
Example with childs :
public class Manufacturer
{
public string Name{ get; set; }
public List<Motor> AvailaibleMotors{ get; set; }
public string getClassSerialized()
{
return new JavaScriptSerializer().Serialize(this);
}
public ManufacturergetClassDeSerialized(string sSerializedClass)
{
return new JavaScriptSerializer().Deserialize<Manufacturer>(sSerializedClass);
}
}
public class Motor
{
public string Model { get; set; }
public List<Voltage> Voltages { get; set; }
}
public class Voltage
{
public int Volt { get; set; }
public int Phase { get; set; }
public int Frequency { get; set; }
}
so manufacturer can have one or many motors which can have one of many voltage and this works perfectly no matter what.
You can probably do something like this too.
public ActionResult jsonPull()
{
try
{
using (var webClient = new System.Net.WebClient())
{
webClient.Encoding = Encoding.UTF8;
var json = webClient.DownloadString("example.com/json");
var parsed = JsonConvert.DeserializeObject(json);
return Json(parsed);
}
}
catch (Exception e)
{
return Json(new { json = "error" });
}
}