如果你不喜欢用XML来配置,一个好的办法是用attribute来配。这个attribute的包在sourceforge有下的,2.0版的也有了个beta的可以用,看来还是不错的。
在SharpDevlop里面对attribute的支持不太好,提示功能不强,VS2008要好一些,但感觉还是没有XML好。
例子还是上次的三个关系里面的,但这次只是给出了带attribute的cs文件,后面有一个生成xml的代码。
先还是1对1的例子。
- [Class]
- public class Person
- {
- public Person()
- {
- }
- [Id(0, TypeType=typeof(int))]
- [Generator(1, Class="native")]
- virtual public int ID {get; set;}
- [Property]
- virtual public int Age {get; set;}
- [Property]
- virtual public string Name {get; set;}
- [OneToOne(ClassType=typeof(Passport))]
- virtual public Passport Passport {get; set;}
- }
- [Class]
- public class Passport
- {
- public Passport()
- {
- }
- [Id(0, TypeType=typeof(int))]
- [Generator(1, Class="foreign")]
- [Param(2, Name="property", Content="Person")]
- virtual public int ID {get; set;}
- [Property]
- virtual public string Expire {get;set;}
- [OneToOne(ClassType=typeof(Person))]
- virtual public Person Person{get;set;}
- }
然后是1对多的
- [Class]
- public class Parent
- {
- public Parent()
- {
- }
- [Id(0, TypeType = typeof(int))]
- [Generator(1, Class = "native")]
- virtual public int ID { get; set; }
- [Set(0, Inverse = true, Lazy = true)]
- [Key(1, Column = "parent_id")]
- [OneToMany(2, ClassType = typeof(Child))]
- virtual public ISet<Child> Children { get; set; }
- }
- [Class]
- public class Parent
- {
- public Parent()
- {
- }
- [Id(0, TypeType = typeof(int))]
- [Generator(1, Class = "native")]
- virtual public int ID { get; set; }
- [Set(0, Inverse = true, Lazy = true)]
- [Key(1, Column = "parent_id")]
- [OneToMany(2, ClassType = typeof(Child))]
- virtual public ISet<Child> Children { get; set; }
- }
最后是多对多的
- [Class]
- public class Parent
- {
- public Parent()
- {
- }
- [Id(0, TypeType = typeof(int))]
- [Generator(1, Class = "native")]
- virtual public int ID { get; set; }
- [Set(0, Inverse = true, Lazy = true)]
- [Key(1, Column = "parent_id")]
- [OneToMany(2, ClassType = typeof(Child))]
- virtual public ISet<Child> Children { get; set; }
- }
- [Class]
- public class Lesson
- {
- public Lesson()
- {
- }
- [Set(0, Name="students", Table="student_lesson")]
- [Key(1, Column="student_id")]
- [ManyToMany(2, Column="lesson_id", Class="Demo5.Domain.Student, Demo5")]
- virtual public ISet<Student> students{get;set;}
- [Id(0, TypeType = typeof(int))]
- [Generator(1, Class = "native")]
- virtual public int ID{get;set;}
- virtual public string LessonName{get;set;}
- }
最后给出编译的代码
- [Test]
- public void TestCreateAttibute()
- {
- // TODO: Add your test.
- var stream = new MemoryStream();
- HbmSerializer.Default.Validate = true;
- HbmSerializer.Default.Serialize(stream, Assembly.GetExecutingAssembly());
- stream.Position = 0;
- for(int i=0; i < stream.Length; i++)
- Console.Write((char)stream.GetBuffer()[i]);
- stream.Position = 0;
- var cfg = new Configuration();
- cfg.Configure().AddInputStream(stream);
- new SchemaExport(cfg).Create(true, false);
- }