Two same table's mapping LINQ TO SQL - c#

For some reason, i have two tables(they are called differently) in my database and both are fully the same.
Also, each of them has too many attributes.
So image i have two ORM Models,like this one:
[Table(Name = "DataHelper")]
class MySameTable1
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Surname { get;set; }
[Column]
public string Country { get;set; }
//etc. too much properties
}
and the second one
[Table(Name = "DataSource")]
class MySameTable2
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Surname { get;set; }
[Column]
public string Country { get;set; }
//etc. too much properties
}
So when i'm doing the job with table's:
DataContext _DataContext = new DataContext("connectionstring");
var MySameORM_Model1 = _DataContext.GetTable<MySameTable1>();
var MySameORM_Model2 = _DataContext.GetTable<MySameTable2>();
the main problem occurs,when i need to populate second table(MySameORM_Model2) via data that contains in table MySameTable1(not sometimes it will be directly insert,but sometimes not)
So to not foreach all entries from MySameTable1 , I have tried this steps:
1.Abstract class that contains all properties:
public abstract class BaseSameTable
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Surname { get;set; }
[Column]
public string Country { get;set; }
//etc. too much properties
}
//inheritance
[Table(Name = "DataHelper")]
class MySameTable1 : BaseSameTable
{ }
//same
[Table(Name = "DataSource")]
class MySameTable2 : BaseSameTable
{ }
And it didn't work, I got strange exceptions with hierarchy submission
After this, i have changed abstract class to interface abstraction, but unfortenuly it didn't make the trick.
public interface IBaseEntity
{
int Id { get; set; }
string Name { get; set; }
string Surname { get;set; }
string Country { get;set; }
//etc. too much properties
}
[Table(Name = "DataHelper")]
class MySameTable1 : IBaseEntity
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Surname { get;set; }
[Column]
public string Country { get;set; }
//etc. too much properties
}
[Table(Name = "DataSource")]
class MySameTable2 : IBaseEntity
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Surname { get;set; }
[Column]
public string Country { get;set; }
//etc. too much properties
}
So what is the right approach for my case and what can I do to achieve my goal?
Maybe it needs additional mappings, but google didn't help me.

If your data is going from one table to another table, why get your host machine involve at all? Wite a stored procedure to handle it, so the data never has to leave the dataserver.

Related

wpf listview - show real name instead of id

I did make a class:
public class VerzekeringDossier
{
public VerzekeringDossier()
{
}
public int Id { get; set; }
public string DossierNummer { get; set; }
public int Gebouw { get; set; }
public string Adres { get; set; }
public string Schadelijder { get; set; }
public string SchadeVeroorzaker { get; set; }
}
and
class Gebouw
{
public Gebouw()
{
}
public int Id { get; set; }
public string GebouwNaam { get; set; }
}
Verzekeringdossier table:
Gebouw table:
And my listview looks like this:
As you can see, in table gebouw, there is the id, but i want ti change it to the name of gebouw with the correct id. Can someone give me a hint?
more than a hint I can give you a track.
Your first class contains an int for the id that is public, it could be way more interesting to have a private field which contains the id and a public acces for the object Gebouw.
...
private int _id {get;set;}
public Gebouw gebouw => method_to_get_Gebouw(_id);
...
And to display the name you can simply override the toString method in the Gebouw class
...
public override string ToString()
{
return GebouwNaam;
}
...
Hope it can help you !

How to stop abstract class attributes to be pass in end result - WebAPI?

I have following scenario where I am getting OrderBase obstract class from ThirdParty library. And I have to inherit this abstract class into my model Order to get base attributes. Only below base attributes are required to be return as part of response.
Id
Name
OrderHistory
But actually it return all the base attributes as part of response due to inheritance. So is there any way by which we can restrict no of base attributes to be pass in the result without introduction of intermediate model(s) and mappings.
Code Sample- Third Party:
[DataContract]
[Serializable]
public abstract class OrderBase
{
public OrderBase(DatabaseObject obj)
{
this.Id = obj.Id;
this.Name = obj.Name;
this.Description = obj.Description;
this.ClosingDate = obj.ClosingDate;
this.Price = obj.Price;
}
[DataMember]
public string Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public decimal Price { get; set; }
[DataMember]
public string ClosingDate { get; set; }
}
public class DatabaseObject
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string ClosingDate { get; set; }
public string OrderHistory { get; set; }
}
Model:
[DataContract]
[Serializable]
public class Order : OrderBase
{
public Order(DatabaseObject dbObject)
: base(dbObject)
{
this.OrderHistory = dbObject.OrderHistory;
}
[DataMember]
public string OrderHistory { get; set; }
}
API Code:
public class OrderController : ApiController
{
public Order GetOrder()
{
var dbObj = new DatabaseObject
{
Id = "O001",
Name = "Masala Packets",
ClosingDate = "01/02/2016",
Description = "Payment Successful",
OrderHistory = "",
Price = 10000
};
var orderObj = new Order(dbObj);
return orderObj;
}
}
Current JSON Result:
{
"OrderHistory": "",
"Id": "O001",
"Name": "Masala Packets",
"Description": "Payment Successful",
"Price": 10000.0,
"ClosingDate": "01/02/2016"
}
Expected JSON Result:
{
"OrderHistory": "",
"Id": "O001",
"Name": "Masala Packets"
}
You're serializing your domain models directly. That may not be a good idea. It's better to create a view model to send your serialized data and you will have complete control of what to serialize as well as better separation of concerns. Something like an OrderDTO
public class OrderDTO {
public string Id { get; set; }
public string Name { get; set; }
public string OrderHistory { get; set; }
}
In your web api method:
public class OrderController : ApiController
{
public OrderDTO GetOrder()
{
// return an OrderDTO instead;
}
}
Or you can use JsonIgnore property to exclude properties from serialization in case you want to expose your domain classes:
[DataContract]
[Serializable]
public abstract class OrderBase
{
public OrderBase(DatabaseObject obj)
{
this.Id = obj.Id;
this.Name = obj.Name;
this.Description = obj.Description;
this.ClosingDate = obj.ClosingDate;
this.Price = obj.Price;
}
[DataMember]
public string Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
[JsonIgnore]
public string Description { get; set; }
[DataMember]
[JsonIgnore]
public decimal Price { get; set; }
[DataMember]
[JsonIgnore]
public string ClosingDate { get; set; }
}
Use the [ScriptIgnore] attribute on the property you don't want to serialize as JSON.
If you don't want to do this in the parent class, you should shadow or overload the property in your child class and add the attribute there.
How to exclude property from Json Serialization

converting the dataset tables to WCF data member class type

I am retrieving relational dataset( 2 tables) from DB.
I have a DataContract defined like below :
public class DetailData
{
[DataMember]
public Customer_Detail Detail;
[DataMember]
public Relationship_Detail Relationship_Detail;
}
[DataContract(Name = "Detail")]
public class Customer_Detail
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string NAME { get; set; }
}
[DataContract(Name = "Relationship Detail")]
public class Relationship_Detail
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string STATUS { get; set; }
}
Now In My data access layer I need to assign the dataset table1 value to "Customer_Detail" and the second table value to "Relationship_Detail".
How can I achieve this?
Appreciate your help in advance.
Something like this -
obj.Prop1 = ds.Tables[0].Rows.Cast<DataRow>().Select(a => new Test{ Name = a.Field<int>("Name"), Age = a.Field<string>("Age") }).ToList();
obj.Prop2 = ds.Tables[1].Rows.Cast<DataRow>().Select(a => new Test2{ Name2 = a.Field<int>("Name"), Age2 = a.Field<string>("Age") }).ToList();

Ria Services and navigation property issues

I'm encountering an issue using Silverlight4, Ria Services and Entity Framework.
From my sl client I try to get some data through ria services, in my domainService class this method gets called:
public IQueryable<LastMinuteWachtLijstPromotie> GetLastMinuteWachtLijstPromoties(){
IQueryable<LastMinuteWachtLijstPromotie> list = (IQueryable<LastMinuteWachtLijstPromotie>)this.ObjectContext.LastMinuteWachtLijstPromoties.Include("Promotie");
return (from LastMinuteWachtLijstPromotie lwmp in list where lwmp.Actief select lwmp);
}
when I check the contents of the list, in debug mode, it's filled with objects of type LastMinuteWachtLijstPromotie.
these objects have a navigation property to an Object named Promotie.
And i can access the properties of these Promotie objects.
On the silveright client however a method gets invoked when loading is complete:
public void OnLoadEntitiesCompleted(ServiceLoadResult<T> result) {
}
In this method I get all the requested LastMinuteWachtLijstPromotie objects as expected, the property
Promotie however is null.
I have set the [Include] tag on the property Promotie in the auto generated metadata class
and I use the .Include("Promotie")
These same methods are used for different objects from my Domain Model, this works perfectly.
Also, I cannot seem to find differences in the .edmx file with the database mappings and navigation properties.
Has anyone encountered the same issue or know a solution for it?
the metadata classes:
[MetadataTypeAttribute(typeof(LastMinuteWachtLijstPromotie.LastMinuteWachtLijstPromotieMetadata))]
public partial class LastMinuteWachtLijstPromotie
{
// This class allows you to attach custom attributes to properties
// of the LastMinuteWachtLijstPromotie class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class LastMinuteWachtLijstPromotieMetadata
{
// Metadata classes are not meant to be instantiated.
private LastMinuteWachtLijstPromotieMetadata()
{
}
public int AlertId { get; set; }
public string ArtikelNummer { get; set; }
public Nullable<int> ArtikelVariant { get; set; }
public int LastMinuteWachtLijstPromotieId { get; set; }
[Include]
public Promotie Promotie { get; set; }
public int PromotieArtikelId { get; set; }
public int PromotieId { get; set; }
public bool Actief { get; set; }
public DateTime Aanmaakdatum { get; set; }
}
}
[MetadataTypeAttribute(typeof(Promotie.PromotieMetadata))]
public partial class Promotie
{
// This class allows you to attach custom attributes to properties
// of the Promotie class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class PromotieMetadata
{
// Metadata classes are not meant to be instantiated.
private PromotieMetadata()
{
}
public string ActieType { get; set; }
public string AssortimentsManagerNaam { get; set; }
public string AssortimentsManagerTeamIds { get; set; }
[Display(Name = "Commerciele tekst")]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Nokavision.ReclameFolder.UI.Web.Resources.ValidationResources))]
public string CommercieleTekst { get; set; }
[Display(Name = " ")]
public string CommercieleTekstDetails { get; set; }
[Include]
public Frame Frame { get; set; }
public Nullable<int> FrameId { get; set; }
public Nullable<DateTime> LastMinuteWijzigingsDatum { get; set; }
public string Opmerkingen { get; set; }
[Display(Name = "Op wachtlijst")]
public Nullable<bool> OpWachtLijst { get; set; }
//public Nullable<int> PromotieCopyId { get; set; }
public int PromotieId { get; set; }
[Include]
public EntityCollection<PromotieLeverancier> PromotieLeveranciers { get; set; }
[Include]
public EntityCollection<PromotieMutatie> PromotieMutaties{ get; set; }
//public Nullable<int> PromotieOrigineleId { get; set; }
[Include]
public EntityCollection<PromotieSymbool> PromotieSymbolen { get; set; }
public string Status { get; set; }
[Display(Name = "Promotie inhoud")]
public string PromotieInhoud { get; set; }
[Display(Name = "Promotie eenheid")]
public string PromotieEenheid { get; set; }
[Display(Name = "Promotie prijs")]
public decimal PromotiePrijs { get; set; }
}
}
Add the Composition attribute to the property Promotie property of the LastMinuteWachtLijstPromotieMetadata class. Then it should work.
public partial class LastMinuteWachtLijstPromotie {
internal sealed class LastMinuteWachtLijstPromotieMetadata{
[Include]
[Composition]
public Promotie Promotie { get; set; }
}
}
I know this is an older thread and it may well have been answered elsewhere but I just stumbled upon it and since nobody has provided a link or a better answer.
I'm currently using Silverlight 5 and this is what worked for me (I think the process is the same in SL4 IIRC).
When propegating navigation properties to the client you need to tell RIA services that there is a relationship somewhere using the [Key] and [Association] attributes, this, not unlike the entity framework just describes how to map the relationship to the proper object.
First the metadata classes:
[MetadataTypeAttribute(typeof(Category.CategoryMetadata))]
public partial class Category
{
internal sealed class CategoryMetadata
{
private CategoryMetadata() {
}
[Key]
public int Id { get; set; }
public string NAME { get; set; }
[Association("CategoryToProducts", "Id", "CAT")]
[Include]
public EntityCollection<Product> Products { get; set; }
}
}
[MetadataTypeAttribute(typeof(Order.OrderMetadata))]
public partial class Order
{
internal sealed class OrderMetadata
{
// Metadata classes are not meant to be instantiated.
private OrderMetadata() {
}
[Key]
public int Id { get; set; }
public int PRODID { get; set; }
public DateTime DATE { get; set; }
public bool DONE { get; set; }
public int QTY { get; set; }
[Association("OrderToProduct", "PRODID", "Id", IsForeignKey = true)]
[Include]
public Product Product { get; set; }
}
}
[MetadataTypeAttribute(typeof(Product.ProductMetadata))]
public partial class Product
{
internal sealed class ProductMetadata
{
private ProductMetadata() {
}
[Key]
public int Id { get; set; }
public int CAT { get; set; }
public string NAME { get; set; }
public string DESC { get; set; }
public decimal PRICE { get; set; }
public int QTY { get; set; }
public long UPC { get; set; }
[Association("ProdToCat", "CAT", "Id", IsForeignKey = true)]
[Include]
public Category Category { get; set; }
[Association("ProductToOrders", "Id", "PRODID")]
[Include]
public EntityCollection<Order> Orders { get; set; }
}
}
Now we need to tell RIA services we want it to load the association:
(Note: Intellisense says it's a dot separated list of property names to include, however I tried something like .Include("Category.SubCategory") and this failed with an exception... though .Include("Category").Include("SubCategory") worked like a charm!)
public IQueryable<Product> GetProducts() {
return this.ObjectContext.Products.Include("Category");
}
I can now access my "Category" property from the Silverlight client and it is not NULL :)
Same as SilverX: just had the issue, solved it and thought it could be useful to someone.
I too had all the configuration stuff correct ([Include] for RIA S, Include() for EF) but a navigation property was still null on the Silverlight side.
Turns out the domain service method was using the [Invoke] attribute (and returning a IEnumerable<T>). Removing this attribute solved the issue.
(just for the record, [Invoke] was being used because the method had a List<Entity> parameter)

LINQ to SQL with Lazy Loading map classes correcly

this is first time i am doing this, when i want to add new item to the db it fails.
How shall set property of ArticleCategoryId in article class to reference the article category in article as at the moment it is null and does not contain any value? My classes is as follows:
Class for articles:
[Table(Name="Articles")]
public class Article
{
[HiddenInput(DisplayValue=false)]
[Column(IsPrimaryKey=true, IsDbGenerated=true,AutoSync=AutoSync.OnInsert)]
public int ArticleId { get; set; }
[Column(Name="ArticleCategoryId", AutoSync = AutoSync.Never)]
[Mapping.Association(IsForeignKey = true, Name = "FK_Articles_ArticleCategorys")]
public ArticleCategories ArticleCategory{get;set;}
[Column]
public string Label { get; set; }
[DataType(DataType.MultilineText)]
[Column]
public string Text { get; set; }
[DataType(DataType.DateTime)]
[Column]
public DateTime Created { get; set; }
}
Class for categories:
[Table(Name = "ArticleCategorys")]
public class ArticleCategories
{
[HiddenInput(DisplayValue = false)]
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert, Name="ArticleCategoryId")]
public int ArticleCategoryId { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Description { get; set; }
[DataType(DataType.DateTime)]
[Column] public DateTime Created { get; set; }
}
My error:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "ArticleId")] Article article)
{
try
{
ArticleCategories category = articleCategoriesRepository.ArticleCategories.FirstOrDefault(x => x.ArticleCategoryId == article.ArticleCategory.ArticleCategoryId);
article.ArticleCategory = category;
article.Created = DateTime.Now;
articlesRepository.SaveArticle(article);
ViewData["Message"] = NudaJeFuc.WebUI.Properties.Resources.text_ArticleSaved;
return RedirectToAction("Index");
}
catch
{
return view();
}
}
I ran into an issue with Linq2SQL mapping, where it does not update when you add new columns to the database, and therefore will fail.
So I would have to delete the .edmx file and re-add it anytime I made changes to the database.
This doesn't happen with ADO.NET Entity Framework, so try that if you can.
found solution, thanks to Steven Sanderson
[Table(Name="Articles")]
public class Article
{
[HiddenInput(DisplayValue=false)]
[Column(IsPrimaryKey=true, IsDbGenerated=true,AutoSync=AutoSync.OnInsert)]
public int ArticleId { get; set; }
[Column]
internal int ArticleCategoryId { get; set; }
internal EntityRef<ArticleCategories> _ArticleCategoryId;
//[Column(AutoSync = AutoSync.OnInsert, Name = "ArticleCategoryId")]
[Association(ThisKey="ArticleCategoryId", Storage="_ArticleCategoryId")]
public ArticleCategories ArticleCategory
{
get
{
return _ArticleCategoryId.Entity;
}
set
{
ArticleCategoryId = value.ArticleCategoryId;
_ArticleCategoryId.Entity = value;
}
}
[Column]
public string Label { get; set; }
[DataType(DataType.MultilineText)]
[Column]
public string Text { get; set; }
[Required(ErrorMessage = "Musíte vybrat kategorii článku.")]
[DataType(DataType.DateTime)]
[Column]
public DateTime Created { get; set; }
}

Categories

Resources